如何用其他数据帧对一列的值进行分类?

2024-09-27 21:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据标准的数据框架对一个数据进行分类。 像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

Tags: 数据框架标准分类czresultradf1
2条回答

让我们用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

选项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
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

注意这里数据的顺序改变了,但是答案保持不变。你知道吗

相关问题 更多 >

    热门问题