简体   繁体   English

如何使用dataframe在python中生成唯一的服务id号

[英]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: 大家好我有一个数据,有两个cloumns所以想要生成唯一的id序列... 这是数据:

    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: 我想将这个服务id加入到这两个列中,因为我已经编写了一个代码:

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: 但我不想像这样的“Sr_ID”我想要像“Sr_0001 ... Sr_0002”它应该是一个数字序列这个“Sr”所以为此我想要一个像这样的输出:

    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. 我想为不同的行生成不同的id,因为我有8列,没有重复的行。

np.arange + str.zfill 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM