用于唯一值的Python Pandas列值增量计数器

ewm0tg9j  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(111)

假设我有一个序列(假设这是一个包含许多列的 Dataframe ,但我现在只关心df["Key"]):

Key
----
1234
1234
1234
5678
6789
7890
7890
6789
2345

如何创建一个名为“Counter”的新列,使"Key"?中的匹配值递增,如下所示:

Key     Counter
----    -------
1234       1
1234       2
1234       3
5678       1
6789       1
7890       1
7890       2
6789       2
2345       1

我不需要每个唯一值的总计数的摘要...我知道您可以通过执行类似df["Key"].value_counts()df.groupby('Key').count()的操作来获取唯一计数的值

yh2wf1be

yh2wf1be1#

按累计使用PD分组:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html
它Map到0-n,因此可以选择在结果中加1:

out = df.groupby('Key').cumcount() + 1
ajsxfq5m

ajsxfq5m2#

试试看:

df["Counter"] = df.groupby("Key").cumcount().reset_index(drop=True) + 1

这将产生预期结果:

Key  Counter
0  1234        1
1  1234        2
2  1234        3
3  5678        1
4  6789        1
5  7890        1
6  7890        2
7  6789        2
8  2345        1

相关问题