我有两个数据帧,Dataframe1有三列:uniquid,poistion1(x,y位置)和位置2(x,y位置),而Dataframe2有四列:顶部,底部,左侧和右侧,每列都有(x,y位置)值。两个数据框的行数都不同。
DataFrame1
Unique Id Position 1 Position 2
1 (28, 50) (49, 94)
2 (18, 181) (616, 90)
3 (578, 253) (15, 182)
4 (600, 96) (44, 307)
DataFrame2
Top Bottom Left Right
(25,30) (445,25) (846,52) (16, 180)
(46, 307) (569, 264) (28, 50) (22, 185)
(36, 201) (95, 330) (49, 94)
(600, 96) (616, 90)
我想搜索与datafram2的哪一列匹配的position1的每个值?假设position1的第一个值(28,50)在DataFrame2的Left列中可用,然后在dataFrame1中,在newposition1中写入唯一ID,则应该写入column name + uniqueID(例如“ Left1”)。如果该值在Dataframe2的任何列中均不可用,则输入“ NotFound”。与position2相同。
预期输出:
DataFrame1
Unique Id Position 1 Position 2 newposition1 newposition2
1 (28, 50) (49, 94) Left1 Right1
2 (18, 181) (616, 90) NotFound Bottom2
3 (578, 253) (15, 182) NotFound NotFound
4 (600, 96) (44, 307) Top4 NotFound
我尝试了几种解决方案,但对我没有用。任何帮助将非常感激。谢谢你。
在df2上使用Dataframe.melt
,并在map
上使用值:
df["newpos1"] = df["Position 1"].map(df2.melt().dropna().set_index("value")["variable"]) + df["Unique Id"].astype(str)
print (df)
Unique Id Position 1 Position 2 newpos1
0 1 (28, 50) (49, 94) Left1
1 2 (18, 181) (616, 90) NaN
2 3 (578, 253) (15, 182) NaN
3 4 (600, 96) (44, 307) Top4