Py学习  »  Python

Python比较两个数据帧的列并生成匹配行的索引

Mainland • 5 年前 • 1531 次点击  

ref_df = 
   condition          color
0     normal              g
1    onesoil         silver
2    sixsoil              k
3     crack1           pink
4     crack2         tomato
5    crack3a     lightcoral
6    crack3b      indianred
7     crack4      orangered
8    intcon1      turquoise
9    intcon2  lightseagreen
10  modcont1        hotpink
11  modcont2       deeppink

test_df = 
index
intcon1     71.046122
intcon2     70.925799
modcont1    70.061561
crack2      71.484572
crack3a     71.703785
crack3b     71.352460
crack4      72.214675

我想比较测试数据和参考数据,得出参考数据的结果。在上面的例子中,我想比较test_df的索引和ref_df['condition']的索引,并且我想为匹配的行生成ref_df['color']的结果。我想在一行代码中实现所有功能。 我现在的密码

 color_df = expdf['color'].loc[expdf['condition'].isin(faultdf.index)]

我目前的产出:

0                 g
1            silver
2                 k
4            tomato
5        lightcoral
6         indianred
7         orangered
8         turquoise
9     lightseagreen
10          hotpink
11         deeppink

预期产量

8    turquoise
9    lightseagreen
10   hotpink
4    tomato
5    lightcoral
6    indianred
7     orangered

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53606
 
1531 次点击  
文章 [ 1 ]  |  最新文章 5 年前
U10-Forward
Reply   •   1 楼
U10-Forward    5 年前

尝试使用:

color_df = expdf.loc[expdf['condition'].isin(faultdf.index), 'color']

你差点就搞定了, 'color'

编辑:

订购数据帧:

color_df = expdf[expdf['condition'].isin(faultdf.index)].set_index('condition').reindex(fault_df.index).reset_index()