Home > Enterprise >  Reversing the counting direction of a counter
Reversing the counting direction of a counter

Time:08-16

I'm trying to reverse the counter of the following count but I don't know how to do it.

My dataframe looks like this (adf):

Visit - ID Pos(int) Title(str)
randomnumber1 1 rstring
randomnumber1 2 rstring
randomnumber2 1 rstring
randomnumber2 2 rstring
randomnumber2 3 rstring

My code looks like the following:

bdf = (adf.assign(col=adf.groupby('Visit - ID').cumcount() 1)
   .set_index(['Visit - ID','col'])
   .unstack('col')
   .sort_index(level=(1,0), axis=1)
)

bdf.columns = [f'{x}{y}' for x,y in bdf.columns]

Output:

Visit - ID Pos 1 Pos 2 Pos 3
randomnumber1 2 1 NaN
randomnumber2 3 2 1
randomnumber3 3 2 1
randomnumber4 3 2 1
randomnumber5 3 2 1

So the counting is reverse. How do I correct the 'counting direction' so that it looks like the following?

Visit - ID Col 1 Col 2 Col 3
randomnumber1 1 2 3
randomnumber2 1 2 3
randomnumber3 1 2 3
randomnumber4 1 2 3
randomnumber5 1 2 3

CodePudding user response:

You can use cumcount(ascending=False):

import pandas as pd

df = pd.DataFrame({
    'id': [1, 1, 2, 2, 2]
})

df['cc_asc'] = df.groupby('id').cumcount(ascending=True)
df['cc_desc'] = df.groupby('id').cumcount(ascending=False)

df
#    id  cc_asc  cc_desc
# 0   1       0        1
# 1   1       1        0
# 2   2       0        2
# 3   2       1        1
# 4   2       2        0
  • Related