gpt4 book ai didi

python - 将 Pandas 数据框从分类 reshape 为计数

转载 作者:行者123 更新时间:2023-11-28 20:15:50 26 4
gpt4 key购买 nike

我正在尝试用两列 reshape 数据框:ID 和分类,以便每个唯一的分类值都有一列。

这是我的:

   ID Animal
foo cat
foo dog
bar cat
baz cat
biz dog
biz cow
biz dog

这是我想要的:

ID  cat dog cow
foo 1 1 0
bar 1 0 0
baz 1 0 0
biz 0 1 2

我试过:

df.groupby(by='ID').count()

给出:

Index Animal
foo 2
bar 1
baz 1
biz 3

我也试过:

df.pivot_table(values='Animal')
df.stack(level='Animal')

前者抛出DataError: no numeric types to aggregate,后者抛出KeyError: Level Animal must be same as name (None)

最佳答案

我们可以使用crosstab()方法:

In [17]: pd.crosstab(df.ID, df.Animal).rename_axis(None, axis=1)
Out[17]:
cat cow dog
ID
bar 1 0 0
baz 1 0 0
biz 0 1 2
foo 1 0 1

关于python - 将 Pandas 数据框从分类 reshape 为计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45150451/

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