Skip to main content
 首页 » 编程设计

python之Seaborn 热图抛出意外错误

2024年10月01日7daizhj

我正在尝试执行以下代码:

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

请解释我的代码中有什么错误。

请您参考如下方法:

您需要通过 astype 将值转换为 int , 因为 strings:

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

问题是如果以这种方式使用 DataFrame 构造函数并且值至少一列是 string,那么它也会将所有值转换为 strings :

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

解决方案是使用 concat或带有 dicts 的 DataFrame 构造函数:

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)