Home > database >  How can I make a new df column that lists an index of a group?
How can I make a new df column that lists an index of a group?

Time:03-19

Not sure how to put this into words, but how can I make a new DataFrame column like Subject? I just need Subject to be like an index for each Group.

Scores Group Subject
4.85 malware 1
0.61 malware 2
2.47 malware 3
6.49 other reuse 1
6.21 other reuse 2
0.52 other reuse 3
0.49 other reuse 4
1.09 other reuse 5
1.71 inoperable 1
0.90 inoperable 2

CodePudding user response:

Looks like you want to assign indexes to each "Group". You can use groupby cumcount:

df['Subject'] = df.groupby('Group').cumcount()   1

Output:

   Scores        Group  Subject
0    4.85      malware        1
1    0.61      malware        2
2    2.47      malware        3
3    6.49  other reuse        1
4    6.21  other reuse        2
5    0.52  other reuse        3
6    0.49  other reuse        4
7    1.09  other reuse        5
8    1.71   inoperable        1
9    0.90   inoperable        2
  • Related