本文介绍了Seaborn 热图抛出意外错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行以下代码:
导入 seaborn 为 sns将熊猫导入为 pd将 numpy 导入为 np年 = 范围(1949,1961)月 = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']乘客 = pd.Series(np.random.randint(100, 1000, len(year)*len(month)), name='passengers')年 = pd.Series(year * len(month), name='years')月份 = pd.Series(month * len(year), name='months').sort_values().reset_index(drop=True)df = pd.DataFrame([年、月、乘客]).Tdf_flight = df.pivot(index="months", columns="years", values="passengers")sns.heatmap(df_flight, annot=True, fmt="d", linewidths=.5)
它抛出了意外错误:
TypeError: ufunc 'isnan' 不支持输入类型,并且无法根据转换规则 ''safe'' 将输入安全地强制转换为任何受支持的类型
请解释我的代码中有什么错误.
解决方案
您需要通过
I am trying to execute following code:
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)
It was throwing unexpected error:
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''
Kindly explain what is error in my code.
解决方案
You need convert values to int
by astype
, because strings
:
sns.heatmap(df_flight.astype(int), annot=True, fmt="d", linewidths=.5)
Problem is if use DataFrame
constructor this way and values at least one column are string
s, then it convert all values to strings
too:
df = pd.DataFrame([years, months, passengers]).T
print (df.dtypes)
years object
months object
passengers object
Solution is use concat
or DataFrame
constructor with 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)
Or:
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)
这篇关于Seaborn 热图抛出意外错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!