Create Custom Heatmap From Pandas Dataframe
I have a dataframe with 8 rows and 6028 columns. I want to create a heatmap of the 8 rows for the first column (eventually I will create an animation so the map updates reading thr
Solution 1:
The data in your indices needs to be part of the cells and you probably want a pivot. For explanation, I created some similar dataframe with less columns to illustrate what I am doing. I hope this is the structure you are using?
df = pd.DataFrame(index=["Anterior Distal", "Anterior Proximal", "Lateral Distal", "Lateral Proximal"], data={0.:[1,2,3,4], 1.:[5,6,7,8]})
print(df)
>>>
0.01.0
region
Anterior Distal 15
Anterior Proximal 26
Lateral Distal 37
Lateral Proximal 48
As I understand it, you want to explicitly refer to the two parts of your index, so you will need to split the index first. You can do this for example in this way which first uses a pandas method to split the strings and then transforms it to a numpy array which you can slice
index_parts = np.array(df.index.str.split().values.tolist())
index_parts[:,0]
>>> array(['Anterior', 'Anterior', 'Lateral', 'Lateral'], dtype='<U8')
Now, you can add those as new columns
df["antlat"] = index_parts[:,0]
df["distprox"] = index_parts[:,1]
print(df)
>>>
0.01.0 antlat distprox
region
Anterior Distal 15 Anterior Distal
Anterior Proximal 26 Anterior Proximal
Lateral Distal 37 Lateral Distal
Lateral Proximal 48 Lateral Proximal
Then you can create the pivot for the value you are interested in
df_pivot = df.pivot(index="antlat", columns="distprox", values=0.0)
print(df_pivot)
>>>
distprox Distal Proximal
antlat
Anterior 12
Lateral 34
And plot it (note that this is only 2x2, since I did not add Medial and Posterior to the example)
sns.heatmap(df_pivot)
Solution 2:
Why not using directly matplotlib
? :D
import matplotlib.pyplot as plt
plt.imshow(df.reset_index(drop=True).values[:,1:].astype("float"))
Post a Comment for "Create Custom Heatmap From Pandas Dataframe"