Python 将数据帧的每一行与另一行的所有行进行比较
编辑 @ashkangh对原始问题的回答非常好,但问题本身就不那么琐碎了:对于Python 将数据帧的每一行与另一行的所有行进行比较,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,编辑 @ashkangh对原始问题的回答非常好,但问题本身就不那么琐碎了:对于df1而言,并非宽度和厚度的所有可能值,但只给出了最小值和最大值。此外,两个数据帧中的宽度和厚度通常都是浮点数(不是整数) 因此,我有两个数据帧df1和df2: import pandas as pd d1 = {'order_id': range(3), 'width': [[0.9, 3.1], [0.7, 2.5], [1.9, 3.3]], 'thickness': [[9.9,
df1
而言,并非宽度和厚度的所有可能值,但只给出了最小值和最大值。此外,两个数据帧中的宽度
和厚度
通常都是浮点数(不是整数)
因此,我有两个数据帧df1
和df2
:
import pandas as pd
d1 = {'order_id': range(3),
'width': [[0.9, 3.1], [0.7, 2.5], [1.9, 3.3]],
'thickness': [[9.9, 11.1], [11.7, 14.4], [9.1, 13.2]]}
df1 = pd.DataFrame(d1)
df1
order_id width thickness
0 0 [0.9, 3.1] [9.9, 11.1]
1 1 [0.7, 2.5] [11.7, 14.4]
2 2 [1.9, 3.3] [9.1, 13.2]
d2 = {'piece_id': range(10, 15),
'width': [2, 3, 3, 1, 2],
'thickness':[10, 15, 9, 11, 12]}
df2 = pd.DataFrame(d2)
df2
piece_id width thickness
0 10 2 10
1 11 3 15
2 12 3 9
3 13 1 11
4 14 2 12
现在我想找出df2
中的哪些片段适合df1
中的哪些顺序。也就是说,如果df2.width
在df1.width
和df2.thickness
在df1.thickness
中
因此,所需的输出应为:
order_id piece_id width thickness
0 0 10 True True
1 0 11 True False
2 0 12 True False
3 0 13 True True
4 0 14 True False
5 1 10 True False
6 1 11 False False
7 1 12 False False
8 1 13 True False
9 1 14 True True
10 2 10 True True
11 2 11 True False
12 2 12 True False
13 2 13 False True
14 2 14 True True
或者更好(只保留合适的订单id
-件id
对)
我可以使用循环,但是数据帧可能相当大(10^3-10^5行),所以我想知道是否有更智能的解决方案
原始数据帧
(df1
中的width
和thickness
是明确给出的,并且只有整数。)
使用explode
方法和merge
可以得到您的结果:
df1.explode('width').explode('thickness')\
.merge(df2, on=['width', 'thickness'], how='inner')[['order_id', 'piece_id']]
输出:
order_id piece_id
0 0 13
1 0 10
2 2 10
3 1 14
4 2 14
你的答案很好,但问题本身却有点棘手——我已经对问题进行了相应的编辑。
df1.explode('width').explode('thickness')\
.merge(df2, on=['width', 'thickness'], how='inner')[['order_id', 'piece_id']]
order_id piece_id
0 0 13
1 0 10
2 2 10
3 1 14
4 2 14