2

I have this dataframe

df1 = pd.DataFrame(data = {'id':[1,1,1,1,2,2,3],'task':[12,32,12,54,64,21,52]})

I want to group by id and change task values respectively like this

   id  task
0  1   1A   
1  1   2A   
2  1   3A   
3  1   4A   
4  2   1B   
5  2   2B   
6  3   1C

I have done this so far

df1['task']=df1.groupby('id')['task'].transform(lambda x : x.factorize()[0]+1)   

Which gives me

   id  task
0  1   1   
1  1   2   
2  1   1   
3  1   3   
4  2   1   
5  2   2   
6  3   1   

How can I get the alphabets and secondly why in id 1 the task sequence is 1213 but not 1234?

1 Answer 1

5
(df1.groupby('id').cumcount().add(1).astype(str)   # digit
 + df1['id'].add(ord('A') - 1).map(chr))           # letter

0    1A
1    2A
2    3A
3    4A
4    1B
5    2B
6    1C
dtype: object

There are two pieces - the digit, and the letter. Construct each one separately. First, the digits. Your code can be shortened using GroupBy.cumcount. Finally convert this result to a string so we can concatenate it with the letter later.

df1.groupby('id').cumcount().add(1).astype(str)

0    1
1    2
2    3
3    4
4    1
5    2
6    1
dtype: object

This gets the letter for the group.

df1['id'].add(ord('A') - 1).map(chr)

0    A
1    A
2    A
3    A
4    B
5    B
6    C
Name: id, dtype: object

Finally, add the intermediaries to get your final result.

3
  • 1
    Too fast ;) @cs95 i'm goin to post exactly similar solution +1.. Jul 14, 2020 at 11:27
  • 1
    @ShubhamSharma Aight, logging off for the night. Happy answering.
    – cs95
    Jul 14, 2020 at 11:27
  • 2
    don't worry just kidding.. There is always something to learn from you answers. Jul 14, 2020 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.