TypeError: ufunc 'isnan' not supported for the input types - Solution
After generating and transposing the DataFrame, a TypeError occurred: TypeError: ufunc ‘isnan’ not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule “safe”.
2. Cause of the Error
This type of error occurs because the DataFrame has been transposed, and the original DataFrame contains a column with strings. Just like in the example above, the first column contains string values “abcdef”. After transposition, all numbers in the DataFrame also become “object” type instead of “float” or “int” numeric types. Therefore, when we try to plot a heatmap with character types, an error naturally occurs.
If the DataFrame originally contained only numeric types, there would be no issue here.
3. Solution
Knowing the cause, the solution is simple: convert the corresponding numeric columns in the transposed DataFrame to numeric types. Here’s the code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from seaborn import clustermap
import seaborn as sns; sns.set(color_codes=True)
df = pd.DataFrame([["a","b","c","d","e","f"],[1,2,3,4,5,6],[2,3,4,5,6,7],[3,4,5,6,7,8]], columns=list('ABCDEF')).T
df[1] = pd.Series(df[1]).astype(float)
df[2] = pd.Series(df[2]).astype(float)
df[3] = pd.Series(df[3]).astype(float)
g = sns.clustermap(df.iloc[:,1:],cmap="PiYG")
By using pandas’ Series type conversion function ‘astype’ to convert the corresponding columns to ‘float’ type, you can then plot the clustered heatmap.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/245.html
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。