简体   繁体   中英

Problem with building heatmap based on pivot_table


I have a dataframe which has a lot of columns, I will show only important/related columns in this question:

data[['HomePlanet', 'CryoSleep', 'Transported']].head()
 HomePlanet CryoSleep   Transported
0   Europa  False   False
1   Earth   False   True
2   Europa  False   False
3   Europa  False   False
4   Earth   False   True
data[['HomePlanet', 'CryoSleep', 'Transported']].dtypes
HomePlanet      object
CryoSleep      boolean
Transported    boolean
dtype: object

I want to make a heatmap based on this pivot_table:

result_1 = data.pivot_table(columns='HomePlanet', index='CryoSleep', values='Transported')
result_1
HomePlanet  Earth   Europa  Mars
CryoSleep           
False   0.320992    0.400172    0.276982
True    0.656295    0.989023    0.911809

But when I try to build a heatmap with seaborn I get an error:

sns.heatmap(result_1, annot=True, cmap="PiYG_r")
TypeError: Image data of dtype object cannot be converted to float

I tried swapping columns and index in pivot_table but got the same error:

result_2 = data.pivot_table(index='HomePlanet', columns='CryoSleep', values='Transported')
result_2

CryoSleep   False   True
HomePlanet      
Earth   0.320992    0.656295
Europa  0.400172    0.989023
Mars    0.276982    0.911809
sns.heatmap(result_2, annot=True, cmap="PiYG_r")
TypeError: Image data of dtype object cannot be converted to float

What am I doing wrong? How can I build a heatmap based on pivot_table?

Thanks to @JohanC. I looked at the dtypes of result_1 and result_2 and the types were Float64:

result_1.dtypes

Output:

 HomePlanet
Earth     Float64
Europa    Float64
Mars      Float64
dtype: object

I changed all types to float64 with this lines:

for column in result_1.columns:
    result_1[column] = result_1[column].astype('float64')

And now the heatmap finally worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM