gpt4 book ai didi

python - pandas DataFrame 列中重复值的顺序

转载 作者:行者123 更新时间:2023-12-01 04:38:11 25 4
gpt4 key购买 nike

如何在 pandas DataFrame 中添加一个新列来枚举所有重复值。在下面的示例中,B 列中有 3 个重复的 865432 值。我想添加一个列,其中的值 0、1 和 2 与不同的 865432 值关联。

输入表

A       B
0 865432
1 865432
2 134567
3 865432
4 134567
5 222222

输出表

A       B  C
0 865432 0
1 865432 1
3 865432 2
2 134567 0
4 134567 1
5 222222 0

最佳答案

您可以在“B”列上使用 groupby,然后调用 cumcount:

In [345]:

df['C'] = df.groupby('B', as_index=False)['B'].cumcount()
df
Out[345]:
A B C
0 0 865432 0
1 1 865432 1
2 2 134567 0
3 3 865432 2
4 4 134567 1
5 5 222222 0

关于python - pandas DataFrame 列中重复值的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337791/

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