假设的数据集,
df1
num1 num2
27 1
973 3
1410 3
724 1
346 5
df2
a1 a2 c1 c2
27.0 1 red apple
131.0 1 blue banana
2124.0 3 green apple
1345.0 1 red orange
346.0 5 blue grape
我想比较 num1 - a1 和 num2 - a2,如果两个条件相同, 我想将 c1 和 c2 中的值添加到列表中。(假设开头是一个空列表)
状况
如您所见,num1-a1、num2&a2 的形状不同。
仅添加到列表中的值为“c1”和“c2”
(num1, num2, a1, a2 只是用来比较和匹配)
顺序困惑,数据帧大小不同。 (不同的柱长)
输出我想要的
上面的例子,2个匹配,(27-1, 346-5),所以
mylist = [red, apple, blue, grape]
我该怎么做?
感谢您的阅读。
最佳答案
使用Series.str.zfill
与 DataFrame.assign
添加 0
与 df2
匹配,然后 DataFrame.merge
使用默认连接,最后使用 DataFrame.stack
对于 Series
并转换为列表:
mylist = (df1.assign(num1 = df1['num1'].astype(str).str.zfill(4),
num2 = df1['num2'].astype(str).str.zfill(3))
.merge(df2, left_on=['num1','num2'], right_on=['a1','a2'])[['c1','c2']]
.stack()
.tolist())
print (mylist)
['green', 'apple', 'orange', 'melon',
'blue', 'banana', 'purple', 'peach']
关于python - 匹配多列并添加到数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60036009/