如何创建一个ID,每当另一列的前一行为1时ID就会增加1

问题描述 投票:0回答:1

使用Python,我需要创建两个新变量。

[每当另一列的上一行采用值'1'时,累积增加一的值(示例中的JourneyID,并且

]

[每一个(在示例中,请参见JourneyN)每次在另一列的上一行中取值'1'时累积累加一,但在响应者ID每增加1时从1开始累加。

m = df['Purpose'] == 1
df.loc[m, 'JourneyID'] = m.cumsum()

返回df [JourneyID] = [1,1,1,2,1,1,3,1,4]何时应返回[1,1,2,2,3,3,3,4,4]用于ID。

非常感谢您的帮助。

Example of what I need to do

python pandas calculated-columns id data-handling
1个回答
1
投票

它不是超级干净,但是应该可以满足您的需求:

helper = ((df['Purpose']==1).cumsum()+1).shift(1)
helper[0]=1
df['JourneyID'] =  helper

JourneyN我没有完全理解:)

© www.soinside.com 2019 - 2024. All rights reserved.