Reputation: 1069
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.
Upvotes: 2
Views: 1164
Reputation: 862601
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)
Upvotes: 2