Python 从第一个数据帧的两列中查找到第二个数据帧中的一列
我有两个数据帧 其中之一是:Python 从第一个数据帧的两列中查找到第二个数据帧中的一列,python,pandas,Python,Pandas,我有两个数据帧 其中之一是: col1 col2 col3 43 21 2 32 31 4 第二 cl4 cl5 cl6 43 1 "text" 21 0 "text2" 32 1 "text3" 从数据帧1开始,col1和col2的值存在于第二个数据帧的cl4中 如何创建一个条件,从数据帧1中获取col1和col2的值,在数据帧2的cl4中查找,并基于此条件获取cl6的值 范例 df1.col1 == df2.cl4 && df1.co
col1 col2 col3
43 21 2
32 31 4
第二
cl4 cl5 cl6
43 1 "text"
21 0 "text2"
32 1 "text3"
从数据帧1开始,col1和col2的值存在于第二个数据帧的cl4中
如何创建一个条件,从数据帧1中获取col1和col2的值,在数据帧2的cl4中查找,并基于此条件获取cl6的值
范例
df1.col1 == df2.cl4 && df1.col2 == df2.cl4
编辑:
非常感谢。识别后,我可以取cl6的值?你可以使用
s=df['cl6']
jezrael抱歉,我刚刚测试了它,但它不起作用。也许这个查询对理解问题没有帮助。第一步是,对于第一个df,两列具有组合。我想根据这个组合检查第二个数据帧,它有一列,如果这个组合存在于这一列中。当它找到它时,给出文本的结果column@Pozmanski-那么您认为df1.col1==df2.cl4和df1.col2==df2.cl4
?或df1.col1==df2.cl4或df1.col2==df2.cl4
?因为如果然后需要df1.col1==df2.cl4==df1.col2
?@Pozmanski-谢谢你,我现在明白了。比较复杂,给我点时间。
print (df2)
cl4 cl5 cl6
0 43 1 text
1 21 0 text2
2 31 1 text3
3 32 4 text4
#shift column for test next row
df2['a'] = df2['cl4'].shift(-1)
#join together next cl6 value
df2['new'] = df2['cl6'] + ', ' + df2['cl6'].shift(-1)
#remove last row of Dataframe because NaN
df2 = df2.iloc[:-1]
#create list of sets by actual and nex values
df2_sets = [set(x) for x in zip(df2['cl4'], df2['a'].astype(int))]
df1_sets = [set(x) for x in zip(df1['col1'], df1['col2'])]
#compare values and at least one True return True
#filter by boolena indexing
s = df2.loc[[any(x == y for y in df1_sets) for x in df2_sets], 'new']
print (s)
0 text, text2
2 text3, text4
Name: new, dtype: object