![](/img/trans.png)
[英]Comparing 2 columns of two Python Pandas dataframes and getting the common rows
[英]Python comparing columns of two dataframes and producing index of matching rows
我有两个数据框
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 并产生 ref_df 的结果。 在上述情况下,我想将 test_df 的索引与 ref_df['condition'] 进行比较,并且我想为匹配行生成 ref_df['color'] 的结果。 我想在一行代码中实现一切。 我现在的代码
color_df = expdf['color'].loc[expdf['condition'].isin(faultdf.index)]
上面的代码简单地复制了 expdf['color'] 的整列。 我现在的输出:
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
如何从单行代码实现上述目标。
尝试使用:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.