Pandas want to change column data into serial number

Question:

I want to change the "Dut" column into a serial number following the number of each "ITEM"

There are lots of "ITEM"s. So I want to get the number of each item.

as following question
enter image description here

Input data:

data = {'ITEM': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'],
        'Dut': ['None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None'],
        'Stat.1': [37, 84, 54, 62, 89, 30, 74, 25, 30, 57, 34, 56, 78, 64]}
df = pd.DataFrame(data)
Asked By: 888Seeme

||

Answers:

Use groupby_cumcount:

If i want to "Dut" Column data as Dut1,Dut2…Dut9 @ "Item" a not, just nubmer how to change it?

df['Dut'] = 'Dut' + df.groupby('ITEM').cumcount().add(1).astype(str)
print(df)

# Ouput
   ITEM   Dut  Stat.1
0     a  Dut1      37
1     a  Dut2      84
2     a  Dut3      54
3     a  Dut4      62
4     a  Dut5      89
5     a  Dut6      30
6     a  Dut7      74
7     a  Dut8      25
8     a  Dut9      30
9     b  Dut1      57
10    b  Dut2      34
11    b  Dut3      56
12    b  Dut4      78
13    b  Dut5      64
Answered By: Corralien

To change the "Dut" column into a serial number following the number of each "ITEM", you can use the groupby function in Pandas to group the data by the "ITEM" column, and then use the cumcount function to assign a unique sequential number to each row within each group.

Here’s the code to accomplish this:

import pandas as pd

data = {'ITEM': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'],
        'Dut': ['None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None'],
        'Stat.1': [37, 84, 54, 62, 89, 30, 74, 25, 30, 57, 34, 56, 78, 64]}
df = pd.DataFrame(data)

# Group by "ITEM" column and assign sequential numbers to each row within each group
df['Dut'] = df.groupby('ITEM').cumcount() + 1

print(df)

The resulting output will have the "Dut" column updated with sequential numbers for each "ITEM":

Answered By: Oguz Ozcan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.