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”.

《TypeError: ufunc ‘isnan’ not supported for the input types - Solution》

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.

《TypeError: ufunc ‘isnan’ not supported for the input types - Solution》