简体   繁体   中英

Is it possible to add a counter in a dataframe which counts per row and resets to 1 when a value in one of two columns is changed?

I have a dataframe in which I need to create a counter in a new column. The counter should start counting per row. The counter needs to reset to 1 when the value of one of two columns in the dataframe changes. The values in the columns are integers.

DataFrame example:

import pandas as pd 
data = {'Col1':[1, 2, 3, 3, 3, 3, 3, 3, 4, 4 ], 'Col2':[1, 1, 1, 1, 1, 2, 2, 2, 2, 2]}
df = pd.DataFrame(data)
print(df)

I tried this initially, but it doesn't seem to work.

df['Counter'] = df.groupby((df['Col1'] != df['Col1'].shift(1)).cumsum()).cumcount()+1
df['Counter'] = df.groupby((df['Col2'] != df['Col2'].shift(1)).cumsum()).cumcount()+1
print(df)

Desired result:

result = {'Col1':[1, 2, 3, 3, 3, 3, 3, 3, 4, 4 ], 'Col2':[1, 1, 1, 1, 1, 2, 2, 2, 2, 2] ,'Counter':[1, 1, 1, 2, 3, 1, 2, 3, 1, 2]}
result = pd.DataFrame(result)
print(result)

I really hope somebody knows how to do this. Thanks in advance: :)

Try:

df['Counter'] = df.groupby(( (df['Col1'] != df['Col1'].shift(1)) | (df['Col2'] != df['Col2'].shift(1)) ).cumsum()).cumcount()+1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM