Seaborn热图投掷意外错误

时间:2017-05-30 05:38:06

标签: python pandas 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 个答案:

答案 0 :(得分:2)

您需要按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