Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a unique service id number in python using dataframe

Hello guys i have a data which have two cloumns so want to generate unique sequence of id for that... This is data:

    Year    Month   
0   2010    Jan     
1   2010    Feb     
2   2010    Mar     
3   2010    Mar     
4   2010    Mar

I want to join that service id to these two column for that i have write a code:

data['Sr_ID'] = data.groupby(['Month','Year']).ngroup()
data.head()

this give this output:

Year    Month   Sr_ID
0   2010    Jan     20
1   2010    Feb     15
2   2010    Mar     35
3   2010    Mar     35
4   2010    Mar     35 

but i don't want "Sr_ID" like this i want to be like "Sr_0001...Sr_0002" it should be in a sequence of number this "Sr" so for this I want a output like this:

    Year    Month   Sr_ID
 0  2010    Jan     Sr_0001
 1  2010    Feb     Sr_0002
 2  2010    Mar     Sr_0003
 3  2010    Mar     Sr_0004
 4  2010    Mar     Sr_0005

I want to generate different id for different row because I have 8 columns, with no repeated rows.

like image 769
rahul singh Avatar asked Apr 05 '26 17:04

rahul singh


1 Answers

np.arange + str.zfill

You can use a range, then pad with zeros to the left:

df['Sr_ID'] = 'Sr_' + pd.Series(np.arange(1, len(df.index)+1)).astype(str).str.zfill(4)

print(df)

   Year Month    Sr_ID
0  2010   Jan  Sr_0001
1  2010   Feb  Sr_0002
2  2010   Mar  Sr_0003
3  2010   Mar  Sr_0004
4  2010   Mar  Sr_0005
like image 155
jpp Avatar answered Apr 08 '26 05:04

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!