Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: ufunc 'isnan' not supported for the input types, - seaborn Heatmap

I am getting the error when i try to plot a seaborn heatmap

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''

my code is as follows

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_table(r"C:\Results.CST", sep='\s+',header=11, engine = 'python')
df2 = cridim[['Bottom','Location_X','Location_Y',]]  # Bottom , location X and Location  Y are my column labels
df3 = df2.pivot('Location_X','Location_Y','Bottom') # create pivot table for results

plt.figure(figsize=(15,15)) 
pivot_table = df3
plt.xlabel('X',size = 10) 
plt.ylabel('Y',size = 10) 
plt.title('btm CD',size = 10) 
sns.heatmap(pivot_table, annot=False, fmt=".1f", linewidths = 0.5, square = True, cmap = 'RdYlBu', vmin=2900, vmax = 3500) 
plt.show()

In my data consist of 77 rows and 77 columns, of which only 651 have data, the others empty coordinates are indicated as None in the dataframe

Is there a limitation of how many data can seaborn heatmap can plot?

I am not sure why am i getting the above error, I have written it to a csv file and it turns out alright.

in addition, I have try to replace the values to '0' and empty string but it still return the Typeerror

like image 620
SA. Avatar asked Apr 20 '17 14:04

SA.


3 Answers

In my case the DataFrame had no Nan values but the data type was of type object. What worked for me was to coerce the data to float using df = df.astype(float). Plotting using seaborn heatmap was then possible.

like image 86
Jacques MALAPRADE Avatar answered Oct 08 '22 20:10

Jacques MALAPRADE


This error happens when you are trying to draw a graph with seaborn, and some of the values are not numeric.

seaborn tries to coerce all data into numbers, but sometimes this error arises. The solution is that you make sure that you don't have NaNs or strings in your data.

Try using df.astype(float) before calling the seaborn graph library. Make sure that you also don't have any NaNs.

like image 37
xiaxio Avatar answered Oct 08 '22 20:10

xiaxio


To add to @xiaxio's answer, if you are calling this programmatically and want to check whether the data is of a numeric type, you can use if not pd.to_numeric(df[some_column], errors='coerce').isna().any(): return or something like that.

like image 45
marcotama Avatar answered Oct 08 '22 20:10

marcotama