Python 如何在两个数据帧之间循环,以根据dataframe1中给定的值选择要从dataframe2提取的行范围
我有两个大数据帧,价格相同。它们的数据帧大小不同。 第一个数据帧Python 如何在两个数据帧之间循环,以根据dataframe1中给定的值选择要从dataframe2提取的行范围,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个大数据帧,价格相同。它们的数据帧大小不同。 第一个数据帧df1,每个产品有一个价格,第二个数据帧df2,每个产品有多个价格。我需要从df1获取产品和价格,并在df2中找到相应的价格范围(-5.0
df1
,每个产品有一个价格,第二个数据帧df2
,每个产品有多个价格。我需要从df1
获取产品和价格,并在df2中找到相应的价格范围(-5.0df3
df3 = pd.DataFrame()
for index, row in df1.iterrows():
pr1 = float(row['price'])
np1 = (row['product'])
npd = MD + 2
npu = MD - 2
for index, row in df2.iterrows():
np2 = (row['product1'])
if np2L == np1:
df3 = df2[(df2.price1 <= npd) & (df2.price1 <= npu)]
…
df3=pd.DataFrame()
对于索引,df1.iterrows()中的行:
pr1=浮动(第[‘价格’]行)
np1=(第[‘产品’]行)
npd=MD+2
npu=MD-2
对于索引,df2.iterrows()中的行:
np2=(第['product1'行])
如果np2L==np1:
df3=df2[(df2.1
#选择df3的行,其中price1和price之间的绝对差异请添加一个可复制的示例。嗨,Samer,非常优雅的解决方案,没有循环。非常感谢您的帮助。它工作得很有魅力。:)
# set index of df1 copy to product (since it is unique)
df1_c = df1.copy().set_index('product')
# join df2 and df1_c on df2.product1 = df1_c.product
df3 = df2.copy().join(other=df1_c, on='product1')
# select rows of df3 where absolute difference between price1 and price <= 5
df3 = df3[ abs(df3.price1-df3.price) <= 5.0 ].reset_index().drop(['index', 'price'], axis=1)
df3