我正在尝试根据标准数据框对一个数据进行分类。 像df1这样的标准,我想在df1的基础上对df2进行分类。
df1: PAUCode SubClass 1 RA 2 RB 3 CZ df2: PAUCode SubClass 2 non 2 non 2 non 3 non 1 non 2 non 3 non
我想像下面这样得到 df2:
expected result: PAUCode SubClass 2 RB 2 RB 2 RB 3 CZ 1 RA 2 RB 3 CZ
请您参考如下方法:
选项 1
fillna
df2 = df2.replace('non', np.nan)
df2.set_index('PAUCode').SubClass\
.fillna(df1.set_index('PAUCode').SubClass)
PAUCode
2 RB
2 RB
2 RB
3 CZ
1 RA
2 RB
3 CZ
Name: SubClass, dtype: object
选项 2
map
df2.PAUCode.map(df1.set_index('PAUCode').SubClass)
0 RB
1 RB
2 RB
3 CZ
4 RA
5 RB
6 CZ
Name: PAUCode, dtype: object
选项 3
合并
df2[['PAUCode']].merge(df1, on='PAUCode')
PAUCode SubClass
0 2 RB
1 2 RB
2 2 RB
3 2 RB
4 3 CZ
5 3 CZ
6 1 RA
注意这里数据的顺序发生了变化,但答案保持不变。
