使用循环中的变量用 pandas 绘制直方图

Plotting histogram with pandas using variables from a loop

我正在尝试绘制一个直方图来显示每个月的支出平均值。从我的 table 来看,我每个月都有不止一个值。

月=["January","February","March","April","May","June","July", "August","September","October","November","December"] 对于范围 (0,12) 中的 k: DataMonth=pd.Series(df.Spendings).where(df.Month==month[k])

print "The average spending in ",month[k]," is", DataMonth.mean()
import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame(
    [['Jan', 2], ['Feb', 3], ['Jan', 8]], 
    columns=['Month', 'Spendings']
)

首先计算平均支出:

mean_spendings = df.groupby('Month').Spendings.mean()

然后绘制条形图(我认为你不需要直方图):

mean_spendings.plot.bar()
plt.show()