2024-09-27 21:22:55 发布
网友
我试图根据标准的数据框架对一个数据进行分类。 像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
让我们用reindex
reindex
df1.set_index('PAUCode').reindex(df2.PAUCode).reset_index() Out[9]: PAUCode SubClass 0 2 RB 1 2 RB 2 2 RB 3 3 CZ 4 1 RA 5 2 RB 6 3 CZ
选项1fillna
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
选项2map
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
选项3merge
merge
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
注意这里数据的顺序改变了,但是答案保持不变。你知道吗
让我们用
reindex
选项1
fillna
选项2
map
选项3
merge
注意这里数据的顺序改变了,但是答案保持不变。你知道吗
相关问题 更多 >
编程相关推荐