Python 熊猫:根据数据帧之间的比较,组合不同形状的数据帧
我有两个dfs:Python 熊猫:根据数据帧之间的比较,组合不同形状的数据帧,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我有两个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:
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
和df2
:
1) 第1列匹配,如果这是真的,那么
2) df1['no2']
介于df2['start']
和df2['stop']
之间:
上述示例所需的输出为(不需要start/stop
列,需要所有其他列):
我尝试过的解决方案(复杂,可能不是最有效的):我认为np.where
可以帮我完成,使用下面的代码,然后删除df['merge']=no
的所有行。但它给了我一个只能比较相同标签的系列对象的错误,我认为这与dfs的大小不同有关。效率/速度很重要,所以我认为即使我可以解决错误,这也不是解决问题的方法
df2['merge'] = np.where((df1['no1'] == df2['no1'] & df2['start'] < df1['no2'] < df2['stop']), yes, no)
df2['merge']=np.其中((df1['no1']==df2['no1']&df2['start']
外部合并
merged = pd.merge(df1, df2, how='outer')
然后按行过滤
>>> merged[(merged.start <= merged.no2) & (merged.no2 <= merged.stop)][['no1', 'start', 'stop', 'other2']]
no1 start stop other2
0 1 2 40 dog
8 3 5 15 dog
>>合并[(merged.start
>>> merged[(merged.start <= merged.no2) & (merged.no2 <= merged.stop)][['no1', 'start', 'stop', 'other2']]
no1 start stop other2
0 1 2 40 dog
8 3 5 15 dog