gpt4 book ai didi

python - Pandas 数据框 : how to add column with number of occurrences in other column

转载 作者:太空狗 更新时间:2023-10-30 02:18:11 26 4
gpt4 key购买 nike

我必须遵循 df:

Col1    Col2
test Something
test2 Something
test3 Something
test Something
test2 Something
test5 Something

我想得到

Col1    Col2          Occur
test Something 2
test2 Something 2
test3 Something 1
test Something 2
test2 Something 2
test5 Something 1

我试过使用:

df["Occur"] = df["Col1"].value_counts()

但这并没有帮助。我有充满“NaN”的 Occur 列

最佳答案

您还可以使用 GroupBy + transformsize:

df['Occur'] = df.groupby('Col1')['Col1'].transform('size')

print(df)

Col1 Col2 Occur
0 test Something 2
1 test2 Something 2
2 test3 Something 1
3 test Something 2
4 test2 Something 2
5 test5 Something 1

关于python - Pandas 数据框 : how to add column with number of occurrences in other column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077898/

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