如何在python数据框中基于两列的组合创建唯一代码

如何在python数据框中基于两列的组合创建唯一代码,python,python-3.x,Python,Python 3.x,我正在尝试创建基于两列组合的唯一代码。任何帮助都将非常好。多谢各位 import pandas as pd data = [['ajay','AL'],['ajay','AB'],['ajay','AL'],['Alex','Ac'],['Alex','Ay'],['Alex','Ac'],['Alex','Ac'],['Bob','Ay'],['Clarke','cv']] df = pd.DataFrame(data,columns=['Name','Cat'],dtype=float)

我正在尝试创建基于两列组合的唯一代码。任何帮助都将非常好。多谢各位

import pandas as pd
data = [['ajay','AL'],['ajay','AB'],['ajay','AL'],['Alex','Ac'],['Alex','Ay'],['Alex','Ac'],['Alex','Ac'],['Bob','Ay'],['Clarke','cv']]
df = pd.DataFrame(data,columns=['Name','Cat'],dtype=float)
输入:

    Name Cat
0    ajay  AL
1    ajay  AB
2    ajay  AL
3    Alex  Ac
4    Alex  Ay
5    Alex  Ac
6    Alex  Ac
7     Bob  Ay
8  Clarke  cv
输出:

           Name Cat  code
0    ajay  AL  AJ_1
1    ajay  AB  AJ_2
2    ajay  AL  AJ_1
3    Alex  Ac  AL_1
4    Alex  Ay  AL_2
5    Alex  Ac  AL_1
6    Alex  Ac  AL_1
7     Bob  Ay  Bo_1
8  Clarke  cv  Cl_1

谢谢。

您只需创建一个带有uuid的列,如下所示:

import uuid    
df['code'] = df.apply(lambda x: uuid.uuid1(), axis=1)
或者,如果要合并这两列:

df['code'] = df.apply(lambda row: row.Name + row.Cat, axis=1)

我希望我正确理解了您的问题,此脚本将创建列
code
,其中前两个字符来自列
'Name'
,然后是基于
'Cat'
列的数字:

from itertools import count
from functools import lru_cache
from collections import defaultdict

d = defaultdict(lambda: count(1))

@lru_cache(maxsize=None)
def get_num(n, c):
    return next(d[n])

df['code'] = df.apply(lambda x: '{}_{}'.format(x['Name'][:2].upper(), get_num(x['Name'], x['Cat'])), axis=1)
print(df)
印刷品:

     Name Cat  code
0    ajay  AL  AJ_1
1    ajay  AB  AJ_2
2    ajay  AL  AJ_1
3    Alex  Ac  AL_1
4    Alex  Ay  AL_2
5    Alex  Ac  AL_1
6    Alex  Ac  AL_1
7     Bob  Ay  BO_1
8  Clarke  cv  CL_1

谢谢你的回答,但是我的列值非常大。基本上,列值是长度较大的机构名称。您可以使用row.Name[:3]获取名称的前3个字母,使用row.Cat[:3]获取Cat列的前3个字母