簡體   English   中英

根據列組合在 dataframe 中創建唯一標識符

[英]create unique identifier in dataframe based on combination of columns

我有以下 dataframe:

    id  Lat         Lon         Year    Area    State
50319   -36.0629    -62.3423    2019    90  Iowa
18873   -36.0629    -62.3423    2017    90  Iowa
18876   -36.0754    -62.327     2017    124 Illinois
18878   -36.0688    -62.3353    2017    138 Kansas

我想創建一個新列,它根據LatLonArea列是否具有相同的值來分配唯一標識符。 例如,在這種情況下,第 1 行和第 2 行在這些列中具有相同的值,並將被賦予相同的唯一標識符0_Iowa ,其中Iowa來自State列。 我嘗試使用 for 循環,但有沒有更 Pythonic 的方式來做到這一點?

id       Lat         Lon       Year    Area State   unique_id
50319   -36.0629    -62.3423    2019    90  Iowa    0_Iowa
18873   -36.0629    -62.3423    2017    90  Iowa    0_Iowa
18876   -36.0754    -62.327     2017    124 Illinois    1_Illinois
18878   -36.0688    -62.3353    2017    138 Kansas  2_Kansas

我將 go 與groupby.ngroup設置sort=False用於分組和str.catState連接設置分隔符:

df['Sate'] = (df.groupby(['Lat','Lon','Area'], sort=False)
                .ngroup() 
                .astype(str)
                .str.cat(df.State, sep='_'))

print(df)

      id      Lat      Lon  Year  Area     State        Sate
0  50319 -36.0629 -62.3423  2019    90      Iowa      0_Iowa
1  18873 -36.0629 -62.3423  2017    90      Iowa      0_Iowa
2  18876 -36.0754 -62.3270  2017   124  Illinois  1_Illinois
3  18878 -36.0688 -62.3353  2017   138    Kansas    2_Kansas
1
​

您可以執行groupby.ngroup並添加列 State:

df['unique_id'] = (df.groupby(['Lat', 'Lon','Area'], sort=False).ngroup().astype(str) 
                   + '_' + df['State'])
print (df)
      id      Lat      Lon  Year  Area     State   unique_id
0  50319 -36.0629 -62.3423  2019    90      Iowa      0_Iowa
1  18873 -36.0629 -62.3423  2017    90      Iowa      0_Iowa
2  18876 -36.0754 -62.3270  2017   124  Illinois  1_Illinois
3  18878 -36.0688 -62.3353  2017   138    Kansas    2_Kansas

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM