擅长:python、mysql、java
<p>分组后,您需要重置索引或在调用<code>groupby</code>时使用<code>as_index=False</code>。按照<a href="https://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">post</a>的说法,默认情况下,聚合函数将不会返回正在聚合的组(如果它们是命名列)。相反,分组列将是返回对象的索引。传递<code>as_index=False</code>或随后调用<code>reset_index</code>将返回正在聚合的组(如果它们是命名列)。在</p>
<p>请看下面我试图将您的结果转换成有意义的图表:</p>
<pre><code>import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
df = fooddata.reset_index()
ax = df[['food','sum']].plot(kind='barh', title ="Total Sum per Food Item", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Sum per Food Item", fontsize=12)
ax.set_ylabel("Food Items", fontsize=12)
ax.set_yticklabels(df['food'])
plt.show()
</code></pre>
<p>结果是<a href="https://i.stack.imgur.com/UMSqH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UMSqH.png" alt="this"/></a></p>