gpt4 book ai didi

python - pandas 中项目类别的 Barpots

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:33 25 4
gpt4 key购买 nike

我是 pandas 的新手,不知道如何绘制每个类别 (6, 7) 的条形图,在以下数据框中显示“湿”与其他状态的比例(百分比):

Mine    Category    State
X23 6 Wet
M34 7 Wet
K28 7 Dry
U56 7 Swampy
S90 6 Wet
E35 7 Dry
X67 6 Wet

到目前为止我的努力:

sub =df.groupby(['Category','State==Wet'].sum()
sub.plot(kind='bar')

有人可以帮忙吗?谢谢

编辑:这是要绘制的数据帧输出

Category    Percent “wet”   Percent “non wet”
6 3/3 (100%) 0/3 (0%)
7 1/4 ¾ ( 75 %)

因此 6 和 7 在 x 轴上,然后湿和非湿堆叠在条 (6) 和条 (7) 中。

最佳答案

您可以将自定义函数f1DataFrame构造函数T结合使用:

def f1(x):
return (sum(x == 'Wet') / float(len(x)))*100, (sum(x != 'Wet') / float(len(x)))*100

grouped = df.groupby(['Category'])['State'].apply(f1)

new_cols = ['wet','non-wet']
print pd.DataFrame(zip(*grouped), columns=grouped.index,index=new_cols).T
wet non-wet
Category
6 100.0 0.0
7 25.0 75.0

sub.plot(kind='bar')

关于python - pandas 中项目类别的 Barpots,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36451573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com