根据不同的列值分配唯一值

Nic*_*e.P 1 python group-by dataframe pandas

我知道问题名称有点含糊不清.

我的目标是在我的数据框中根据2列+唯一值分配全局键列.

例如

CountryCode | Accident
   AFG          Car
   AFG          Bike
   AFG          Car
   AFG          Plane
   USA          Car
   USA          Bike
   UK           Car
Run Code Online (Sandbox Code Playgroud)

设Car = 01,Bike = 02,Plane = 03

我的愿望全局密钥格式是[事故] [CountryCode] [UniqueValue]

唯一值是类似[Accident] [CountryCode]的计数

因此,如果Accident = Car和CountryCode = AFG并且它是第一次出现,则全局密钥将为01AFG01

所需的数据框如下所示:

CountryCode | Accident | GlobalKey
   AFG          Car        01AFG01
   AFG          Bike       02AFG01
   AFG          Car        01AFG02
   AFG          Plane      01AFG03
   USA          Car        01USA01
   USA          Bike       01USA02
   UK           Car        01UK01
Run Code Online (Sandbox Code Playgroud)

我尝试运行for循环将Accident Number和CountryCode一起添加

例如:

globalKey = []

for x in range(0,6):
    string = df.iloc[x, 1]
    string2 = df.iloc[x, 2]
    if string2 == 'Car':
        number = '01'
    elif string2 == 'Bike':
        number = '02'
    elif string2 == 'Plane':
        number = '03'
    #Concat the number of accident and Country Code
    subKey = number + string
    #Append to the list
    globalKey.append(subKey)
Run Code Online (Sandbox Code Playgroud)

此代码将提供给我类似01AFG,02AFG基于我赋值.但我想通过计算何时CountryCode和Accident类似的发生来分配一个唯一的值.

我坚持上面的代码.我认为在Pandas中使用map函数应该有更好的方法.

谢谢你的帮助!非常感谢!

Tha*_*nos 5

您可以尝试通过cumcount多个步骤实现此目的,如下所示:

In [1]: df = pd.DataFrame({'Country':['AFG','AFG','AFG','AFG','USA','USA','UK'], 'Accident':['Car','Bike','Car','Plane','Car','Bike','Car']})

In [2]: df
Out[2]: 
  Accident Country
0      Car     AFG
1     Bike     AFG
2      Car     AFG
3    Plane     AFG
4      Car     USA
5     Bike     USA
6      Car      UK

## Create a column to keep incremental values for `Country`
In [3]: df['cumcount'] = df.groupby('Country').cumcount()

In [4]: df
Out[4]: 
  Accident Country  cumcount
0      Car     AFG         0
1     Bike     AFG         1
2      Car     AFG         2
3    Plane     AFG         3
4      Car     USA         0
5     Bike     USA         1
6      Car      UK         0

## Create a column to keep incremental values for combination of `Country`,`Accident`
In [5]: df['cumcount_type'] = df.groupby(['Country','Accident']).cumcount()

In [6]: df
Out[6]: 
  Accident Country  cumcount  cumcount_type
0      Car     AFG         0              0
1     Bike     AFG         1              0
2      Car     AFG         2              1
3    Plane     AFG         3              0
4      Car     USA         0              0
5     Bike     USA         1              0
6      Car      UK         0              0
Run Code Online (Sandbox Code Playgroud)

从那时起,你可以连接你的价值观cumcount,cumcount_type并Country实现你所追求的目标.

也许您想要添加1到不同计数下的每个值,具体取决于您是否要从0或1开始计数.

我希望这有帮助.