答案 0 :(得分:0)
一些选项:
df['NumID_1'] = df.groupby('Country').ngroup() + 1
df['NumID_2'] = df['Country'].factorize()[0] + 1
根据您的需求,您还可以考虑使用熊猫的Categorical
数据类型:
df['NumID_3'] = df['Country'].astype('category')
Country Year Var1 Var2 Var3 NumID NumID_1 NumID_2 NumID_3
0 Brazil 2000 A B C 1 1 1 Brazil
1 Brazil 2001 X Y Z 1 1 1 Brazil
2 Brazil 2002 F F H 1 1 1 Brazil
3 Brazil 2003 P 3 K 1 1 1 Brazil
4 Chile 2000 A B C 2 2 2 Chile
5 Chile 2001 X Y Z 2 2 2 Chile
6 Chile 2002 F F H 2 2 2 Chile
7 Chile 2003 P 3 K 2 2 2 Chile
答案 1 :(得分:0)
尝试通过此操作从国家/地区获取num id:
将熊猫作为pd导入 从pandas.api.types导入CategoricalDtype
标签,唯一性= pd.factorize([[“巴西”,“巴西”,“巴西”,“巴西”,“智利”,“智利”,“智利”,“智利”]
print(“数字表示形式\ n”,标签) print(“ Unique Values:\ n”,唯一性)enter image description here