Pandas:根据数据帧之间的比较组合不同形状的数据帧

2024-10-04 01:36:15 发布

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

我有两个dfs:

df1:
no1    no2    other1
1      10     foo
1      50     foo
1      60     cat
1      70     cat
3      12     cat

df2:
no1    start    stop    other2
1      2        40      dog
1      100      200     dog
3      5        15      dog

我想在以下条件下合并df1和{}:

1)第1列匹配,如果为真,则

2)df1['no2']介于df2['start']和{}:

上例所需的输出是(不需要start/stop列,只需要所有其他列):

^{pr2}$

我尝试过的解决方案(复杂的,可能不是最有效的):我认为np.where可以为我做这件事,使用下面的代码,然后删除{}中的所有行。但是它给了我一个Can only compare identically-labeled Series objects错误,我认为这与dfs的大小不同有关。效率/速度很重要,所以我认为即使我能解决错误,这也不是解决问题的方法。在

df2['merge'] = np.where((df1['no1'] == df2['no1'] & df2['start'] < df1['no2'] < df2['stop']), yes, no)

Tags: foo错误npwherestartcatdf1stop