2017-05-30 51 views
1

我想執行以下代碼:Seaborn熱圖拋出意外錯誤

import seaborn as sns 
import pandas as pd 
import numpy as np 
year = range(1949,1961) 
month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 
passengers = pd.Series(np.random.randint(100, 1000, len(year)*len(month)), name='passengers') 
years = pd.Series(year * len(month), name='years') 
months = pd.Series(month * len(year), name='months').sort_values().reset_index(drop=True) 
df = pd.DataFrame([years, months, passengers]).T 
df_flight = df.pivot(index="months", columns="years", values="passengers") 
sns.heatmap(df_flight, annot=True, fmt="d", linewidths=.5) 

它被扔意外的錯誤:

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

請解釋什麼是我的代碼錯誤。

回答

1

您需要通過astype值轉換爲int,因爲strings

sns.heatmap(df_flight.astype(int), annot=True, fmt="d", linewidths=.5) 

問題是,如果使用DataFrame構造這種方式和價值至少有一列是string S,那麼它所有的值轉換爲strings太:

df = pd.DataFrame([years, months, passengers]).T 

print (df.dtypes) 
years   object 
months  object 
passengers object 

解決方案是使用concatDataFrame構造與dict S:

df = pd.concat([years, months, passengers], axis=1) 

print (df.dtypes) 
years   int64 
months  object 
passengers  int32 
dtype: object 

... 

sns.heatmap(df_flight, annot=True, fmt="d", linewidths=.5) 

或者:

df = pd.DataFrame({'years':years, 'months':months, 'passengers':passengers}) 

print (df.dtypes) 
months  object 
passengers  int32 
years   int64 
dtype: object 

... 

sns.heatmap(df_flight, annot=True, fmt="d", linewidths=.5) 

graph

相關問題