简体   繁体   中英

[Python]How to automatically assign a special index to the dataframe?

I have the follwoing dataframe:

Bank      Date           %     Type
BankA    29/12/2019      1%     A
BankB    20/12/2016      1%     A
BankB    19/12/2016      2%     B
BankA    29/12/2019      1%     B
BankA    29/12/2019      2%     A

I want to create a 4 digit number for creating an Index The logic is that when Bank and Date and % are matched, the 4 digit number will be same as previous. The Index is created by combining Number and Type

Expected output
Number  Bank    Date            %     Type     Index
0001     BankA   29/12/2019      1%     A      0001-A
0002     BankB   20/12/2016      1%     A      0002-A
0003     BankB   19/12/2016      2%     B      0003-B
0001     BankA   29/12/2019      1%     B      0001-B
0004     BankA   29/12/2019      2%     A      0004-A

How can I achieve this?

Try:

df['Number'] = (df.groupby(['Bank','Date','%']).ngroup()+1).astype(str).str.zfill(4)  
df['Index'] = df['Number']+'-'+df['Type']
df

    Bank        Date   % Type Number   Index
0  BankA  29/12/2019  1%    A   0001  0001-A
1  BankB  20/12/2016  1%    A   0004  0004-A
2  BankB  19/12/2016  2%    B   0003  0003-B
3  BankA  29/12/2019  1%    B   0001  0001-B
4  BankA  29/12/2019  2%    A   0002  0002-A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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