I have a dataframe that has an index (words) and a single column (counts) for some lyrics. I am trying to create a heatmap based on the word counts.
Cuenta
Que 179
La 145
Y 142
Me 113
No 108
I am trying to produce the heatmap like this:
df1 = pd.DataFrame.from_dict([top50]).T
df1.columns = ['Cuenta']
df1.sort_values(['Cuenta'], ascending = False, inplace=True)
result = df1.pivot(index=df1.index, columns='Cuenta', values=df1.Cuenta.count)
sns.heatmap(result, annot=True, fmt="g", cmap='viridis')
plt.show()
But, it keeps throwing 'Index' object has no attribute 'levels'
Any ideas why this isn't working? I tried using the index or words as a separate column and still doesn't work.
The data is one-dimensional. The counts are already present in the one (and only) column of the dataframe. There is no meaningless way to pivot this data.
You would hence directly plot the dataframe as a heatmap.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({"Cuenta": [179,145,142,113,108]},
index=["Que", "La", "Y", "Me", "No"])
sns.heatmap(df, annot=True, fmt="g", cmap='viridis')
plt.show()
.set_index
df = pd.DataFrame({"Cuenta": [179,145,142,113,108],
"words": ["Que", "La", "Y", "Me", "No"]})
# given a dataframe of two columns, set the column as the index
df.set_index("words", inplace=True)
ax = sns.heatmap(df, annot=True, fmt="g", cmap='viridis')
sns.heatmap
will result in an IndexError
if passing a pandas.Series
.
.value_counts
create a Series
df['column']
and df.column
create a Series
. Use df[['column']]
instead.# sample data
tips = sns.load_dataset('tips')
# value_counts creates a Series
vc = tips.time.value_counts()
# convert to a DataFrame
vc = vc.to_frame()
# plot
ax = sns.heatmap(data=vc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With