python - pandas - Groupby 加权条形图

标签 python pandas

考虑以下由 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')

enter image description here

我想将两者结合起来并绘制一个按 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)

enter image description here

关于python - pandas - Groupby 加权条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438931/

相关文章:

python - 应该如何实现对 twisted.pb 中备用凭证类型的支持?

Python子进程超时?

python - 以柱状格式打印数据的最佳方式?

python-3.x - Python3 Pandas.DataFrame.info() 错误键 : 30

Python - 使用排序操作列和行 - reshape

python - 从字符串 pandas python 创建一个数据框

python - 在Python中逐列比较两个大文本文件

python - Scrapy部署算法

python - 多列左连接

python - pandas 日期范围意外行为