gpt4 book ai didi

python - Pandas - 从行数中获取汇总数据框

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:52 25 4
gpt4 key购买 nike

给定这个 DataFrame:

    bowl    cookie
0 one chocolate
1 two chocolate
2 two chocolate
3 two vanilla
4 one vanilla
5 one vanilla
6 one vanilla
7 one vanilla
8 one vanilla
9 two chocolate

我想获得以下总结的 DataFrame:

        vanilla     chocolate
one 5 1
two 1 3

除了手动进行:

vanilla_bowl1 = len(df_picks[(df_picks['bowl'] == 'one') & (df_picks['cookie'] == 'vanilla')])
vanilla_bowl2 = len(df_picks[(df_picks['bowl'] == 'two') & (df_picks['cookie'] == 'vanilla')])
chocolate_bowl1 = ...
chocolate_bowl2 = ...

有没有办法用 Pandas 在一次操作中做到这一点?


注意:我查看了 df.pivot(),如果我添加列 count 等于,这将起作用每行 1:

    bowl    cookie      count
0 one chocolate 1
1 two chocolate 1
2 two chocolate 1
3 two vanilla 1
4 one vanilla 1
5 one vanilla 1
6 one vanilla 1
7 one vanilla 1
8 one vanilla 1
9 two chocolate 1

然后

df.pivot(index='bowl', columns='cookie', values='count')

但是,我想知道是否有更直接的方法,不需要首先添加 count 列。

最佳答案

最简洁的方式可能是pandas.crosstab函数:

>>> pandas.crosstab(d.bowl, d.cookie)
cookie chocolate vanilla
bowl
one 1 5
two 3 1

关于python - Pandas - 从行数中获取汇总数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40556597/

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