考虑以下由 10 行组成的 DataFrame。
d = {
'grp_id':[1,2,1,1,1,3,1,1,4,1],
'weight':[1,2,1,1,1,3,1,1,4,4],
'value': [1,2,1,3,2,1,4,1,1,3]
}
df = pd.DataFrame(d)
加权直方图可以通过
df['value'].hist(histtype='bar', weights=df['weight'])
按 grp_id 分组的未加权条形图
df['value'].hist(by=df['grp_id'], histtype='bar')
我想将两者结合起来并绘制一个按 grp_id 分组的加权条形图。
我尝试了以下两种方法但没有成功,因为我都得到了
ValueError
.df['value'].hist(by=df['grp_id'], weights=df['weight'], histtype='bar')
df['value'].hist(by=df['grp_id'], weights='weight', histtype='bar')
ValueError: weights should have the same shape as x
我正在使用的临时解决方案如下。
fig, axes = plt.subplots(2, 2)
for ax,(idx, grp) in zip(axes.flatten(), df.groupby('grp_id')):
grp['value'].hist(weights=grp['weight'], histtype='bar', ax=ax)
但是,我想问一下是否有直接的方法可以用 Pandas 来做到这一点。
最佳答案
我将首先创建一个存储加权值的新数据框:
df['weighted_values'] = df.weight*df.value
df = df.groupby('grp_id')['weighted_values'].sum().to_frame().reset_index()
您可以使用 seaborn 从美学上绘制最终的条形图:
import seaborn as sns
sns.barplot(x = 'grp_id', y = 'weighted_values', data=df)
关于python - pandas - Groupby 加权条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438931/