【问题标题】:pandas - Grouped weighted Bar Chartpandas - 分组加权条形图
【发布时间】:2020-04-13 18:35:56
【问题描述】:

考虑以下由 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 应该与 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 做到这一点。

【问题讨论】:

  • 你能给我们你的例子想要的输出吗?
  • 嗨,产生输出的代码在问题的最后部分给出。在实践中,它对应于每个组的一个子图,每个子图都有一个加权条形图。
  • 因为我不明白,你想对 grp_id 进行分组并在 weight 和 value 列中计算不同的值吗?

标签: python pandas


【解决方案1】:

我将首先创建一个存储加权值的新数据框:

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)

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2017-03-18
    • 2016-12-01
    • 1970-01-01
    • 2017-06-28
    • 2018-04-25
    • 2011-03-01
    相关资源
    最近更新 更多