python 中是否有函数可以对项目在数据帧中出现的时间进行编号?[复制]

Is there a function in python to number the time an item appears in the dataframe? [duplicate]

提问人:haraujo 提问时间:2/9/2022 更新时间:2/9/2022 访问量:34

问:

我正在尝试检查客户端何时出现在我的数据帧中,以便对其他结果进行一些逻辑处理。但是,当客户出现时,我无法编号。我已经得到了它第一次和最后一次出现的时间,我只是在第一次和最后一次之间的间隔内无法得到它。你能帮帮我吗?这是一个示例表,我想要 C 列作为结果。

Date    Customer    Appear
01/01/2021  A   1
01/01/2021  B   1
01/01/2021  C   1
01/02/2021  A   2
01/02/2021  B   2
01/02/2021  C   2
01/03/2021  A   3
01/03/2021  B   3
01/03/2021  C   3
01/04/2021  A   4
01/04/2021  B   4
01/05/2021  A   5
01/05/2021  B   5
01/06/2021  A   6

enter image description here

Python Pandas DataFrame numpy 数据操作

评论

0赞 Park 2/9/2022
什么是预期输出?
1赞 mozway 2/9/2022
df['Appear'] = df.groupby('Customer').cumcount().add(1)
0赞 haraujo 2/9/2022
@SangkeunPark预期输出为 C 列(出现)

答:

1赞 BENY 2/9/2022 #1

您可以尝试使用groupbycumcount

df['new'] = df.groupby('Customer').cumcount()+1
Out[202]: 
0     1
1     1
2     1
3     2
4     2
5     2
6     3
7     3
8     3
9     4
10    4
11    5
12    5
13    6
dtype: int64

评论

0赞 jezrael 2/9/2022
哎哟,这不是为了回答......
0赞 haraujo 2/10/2022
它的工作,就像@mozway帖子一样: df['Appear'] = df.groupby('Customer').cumcount().add(1)