【发布时间】:2018-03-20 03:43:52
【问题描述】:
我正在处理一个数据集,其中包含一个日期时间列和一个我感兴趣的变量。我想做的是将数据分组为 15 分钟组,所以我编写了以下代码,它基本上计算了一个较低的和日期上限并创建一个间隔为 15 分钟的日期时间对象列表。然后在每对日期时间对象之间对我感兴趣的变量求和,并将总和放入一个新的数据框中。但它运行得很慢(处理 75000 行大约需要五个小时),我不知道为什么。谁能指出代码有什么问题?
here 是一个小样本数据,如果您想自己测试代码。
def create_sales_with_intervals(df, tank_id_col='tank_id'):
tank_id = df.iloc[0][tank_id_col]
tank_dates = get_date_range(df)
tank_sales =[]
for idx in tnrange(len(tank_dates) - 1):
t1 = tank_dates[idx]
t2 = tank_dates[idx+1]
sales = get_sales_between(df, t1, t2)
row={}
row['start_date'] = t1
row['end_date'] = t2
row['total_sale'] = sales
row['tank_id'] = tank_id
tank_sales.append(row)
return pd.DataFrame(tank_sales, columns=['tank_id', 'start_date', 'end_date', 'total_sale'])
def get_date_range(df_tank, date_col='date_time', freq='15MIN'):
start_date = df_tank.iloc[0][date_col]
end_date = df_tank.iloc[-1][date_col]
lower_bound = find_interval(start_date, 'lower')
upper_bound = find_interval(end_date, 'upper')
start_date_rounded = round_time(start_date, lower_bound) # Rounds the minute portion of the datetime object to nearest lower bound (0, 15, 30 , 45)
end_date_rounded = round_time(end_date, upper_bound) # Rounds the minute portion of the datetime object to nearest upper bound (0, 15, 30 , 45)
tank_dates = pd.date_range(start_date_rounded, end_date_rounded, freq=freq)
return tank_dates
def get_sales_between(df, t1, t2, date_col='date_time', sale_col='sold'):
cond1 = df[df[date_col] > t1]
cond2 = df[df[date_col] < t2]
idx = cond1.index & cond2.index
total_sale = df.loc[idx.values][sale_col].sum()
return total_sale
【问题讨论】: