如何遍历for循环中的行

2024-04-19 18:47:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在r中有两个数据帧

 df1 
 code     date          time       prod    price
 123      01-01-2018    06:11:00   MS      12
 123      01-01-2018    06:16:12   HS      13
 123      01-01-2018    06:17:12   HS      13
 123      01-01-2018    06:19:00   MS      12
 123      02-01-2018    06:17:12   HS      13
 123      02-01-2018    06:19:00   MS      12

 df2
 code     date         prod      price
 123      01-01-2018   MS        12
 123      01-01-2018   HS        13
 123      02-01-2018   HS        13

我想从df1和df2中筛选出在df1中具有唯一日期的行。我的df1有1000多行,df2只有4行

例如。 在df1中有2个唯一的dates,有两个唯一的产物MSHS。所以我想比较,例如,我想过滤date和prod01-01-2018 & MS行,然后用df2比较相同的日期和时间

我目前正在使用for循环

unique_dates = iss_trans_268559['transaction_date'].unique()   
unique_dates.sort()
unique_products = iss_trans_268559['prodcode'].unique()

for i in range(len(unique_dates)):
   current_date = df1[(df1['date'] == unique_dates[i]) & df1['prod'] == unique_products[i] 
   df2_current = df2[df2['date'] == unique_dates[i]]

我应该在for循环中获得下面的数据帧,然后我可以比较current_datedf2_current中的日期

current_date
 code     date          time       prod    price
 123      01-01-2018    06:11:00   MS      12
 123      01-01-2018    06:19:00   MS      12

 df2_current 
 code     date         prod      price
 123      01-01-2018   MS        12

上面循环中的问题是i将超出unique_productsdf2的界限,我该怎么做?你知道吗


Tags: 数据fordatetimecodeprodcurrentprice
1条回答
网友
1楼 · 发布于 2024-04-19 18:47:51

我想你需要:

dates= df1['date'].unique()
prods = df1['prod'].unique()

import itertools

comb = list(itertools.product(dates, prods))
# [('01-01-2018', 'MS'), ('01-01-2018', 'HS'), ('02-01-2018', 'MS'), ('02-01-2018', 'HS')]

current_date = []
df2_current = []

for i,j in comb:
    current_date.append(df1[(df1['date']==i) & (df1['prod']==j)])
    df2_current.append(df2[(df2['date']==i) & (df2['prod']==j)])

您可以使用current_date[0]df2_current[0]等来访问数据帧。。。你知道吗

相关问题 更多 >