user16993210
user16993210

Reputation:

How to create a heatmap of Pandas dataframe in Python

I'm trying to create a heatmap and I am following the following question:

Making heatmap from pandas DataFrame

My dataframe looks like the following picture:

enter image description here

I tried the following code:

years = ["1860","1870", "1880","1890","1900","1910","1920","1930","1940","1950","1960","1970","1980","1990","2000"]
kantons = ["AG","AI","AR","BE","BL","BS","FR","GE","GL","GR","JU","LU","NE","NW","OW","SG","SH","SO","SZ","TG","TI","UR","VD","VS","ZG","ZH"]
   
df = pd(abs(dfYears), index=years, columns=kantons)

which gives the exception that:

"AG" can not be used as float

So I thought if I need to drop the index column which is not possible.

Any suggestions?

Upvotes: 1

Views: 307

Answers (1)

heilala
heilala

Reputation: 854

When replicating similar data, you can do:

import pandas as pd
import numpy as np

years = ["1860","1870", "1880","1890","1900","1910","1920","1930","1940","1950","1960","1970","1980","1990","2000"]
kantons = ["AG","AI","AR","BE","BL","BS","FR","GE","GL","GR","JU","LU","NE","NW","OW","SG","SH","SO","SZ","TG","TI","UR","VD","VS","ZG","ZH"]
   
df = pd.DataFrame(np.random.randint(low=10000, high=200000, size=(15, 26)), index=years, columns=kantons)
df.style.background_gradient(cmap='Reds')

Pandas has some Builtin Styles for the most common visualization needs. .background_gradient function is a simple way for highlighting cells based on their values. cmap parameter determines the color map based on the matplotlib colormaps.

Upvotes: 1

Related Questions