Skip to main content
 首页 » 编程设计

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

2025年05月04日15freeliver54

我知道问题名称有点模棱两可。

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

例如

CountryCode | Accident 
   AFG          Car 
   AFG          Bike 
   AFG          Car 
   AFG          Plane 
   USA          Car 
   USA          Bike 
   UK           Car 

设汽车 = 01,自行车 = 02,飞机 = 03

我想要的全局键格式是 [Accident][CountryCode][UniqueValue]

唯一值是类似[事故][国家代码]的计数

所以如果 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 

我尝试运行一个 for 循环来将事故号码和国家/地区代码附加在一起

例如:

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) 

此代码将根据我分配的值为我提供类似 01AFG、02AFG 的内容。但我想通过计算 CountryCode 和 Accident 相似时的出现次数来分配一个唯一值。

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

感谢大家的帮助! 非常感谢!

请您参考如下方法:

您可以尝试使用 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 

从那时起,您可以连接 cumcount、cumcount_type 和 Country 的值来实现您的目标。

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

希望对您有所帮助。