Python使用pandas计算当前fair_price与15分钟前最近行fair_price的差值
问题说明
需要在数据集中新增一列,取值规则为:当前行的fair_price减去15分钟前(或时间最接近的前序行)的fair_price,需先匹配到符合时间要求的前序行再计算差值。
现有实现代码如下:
import numpy as np import pandas as pd from datetime import timedelta df = pd.DataFrame(pd.read_csv('./data.csv')) def calculate_15min(row): end_date = pd.to_datetime(row['date']) - timedelta(minutes=15) mask = (pd.to_datetime(df['date']) <= end_date).head(1) price_before = df.loc[mask] return price_before['fair_price'] def calc_new_val(row): return 'show date 15 minutes before, maybe it will be null, nope' df['15_min_ago'] = df.apply(lambda row: calculate_15min(row), axis=1) myFields = ['pkey_id', 'date', '15_min_ago', 'fair_price'] print(df[myFields].head(5)) df[myFields].head(5).to_csv('output.csv', index=False)
所用CSV样本数据:
pkey_id,date,fair_price,15_min_ago 465620,2021-05-17 12:28:30,45080.23,fair_price_15_min_before 465625,2021-05-17 12:28:35,45060.17,fair_price_15_min_before 465629,2021-05-17 12:28:40,45052.74,fair_price_15_min_before 465633,2021-05-17 12:28:45,45043.89,fair_price_15_min_before 465636,2021-05-17 12:28:50,45040.93,fair_price_15_min_before 465640,2021-05-17 12:28:56,45049.95,fair_price_15_min_before 465643,2021-05-17 12:29:00,45045.38,fair_price_15_min_before 465646,2021-05-17 12:29:05,45039.87,fair_price_15_min_before 465650,2021-05-17 12:29:10,45045.55,fair_price_15_min_before 465652,2021-05-17 12:29:15,45042.53,fair_price_15_min_before 465653,2021-05-17 12:29:20,45039.34,fair_price_15_min_before 466377,2021-05-17 12:42:50,45142.74,fair_price_15_min_before 466380,2021-05-17 12:42:55,45143.24,fair_price_15_min_before 466393,2021-05-17 12:43:00,45130.98,fair_price_15_min_before 466398,2021-05-17 12:43:05,45128.13,fair_price_15_min_before 466400,2021-05-17 12:43:10,45140.9,fair_price_15_min_before 466401,2021-05-17 12:43:15,45136.38,fair_price_15_min_before 466404,2021-05-17 12:43:20,45118.54,fair_price_15_min_before 466405,2021-05-17 12:43:25,45120.69,fair_price_15_min_before 466407,2021-05-17 12:43:30,45121.37,fair_price_15_min_before 466413,2021-05-17 12:43:36,45133.71,fair_price_15_min_before 466415,2021-05-17 12:43:40,45137.74,fair_price_15_min_before 466419,2021-05-17 12:43:45,45127.96,fair_price_15_min_before 466431,2021-05-17 12:43:50,45100.83,fair_price_15_min_before 466437,2021-05-17 12:43:55,45091.78,fair_price_15_min_before 466438,2021-05-17 12:44:00,45084.75,fair_price_15_min_before 466445,2021-05-17 12:44:06,45094.08,fair_price_15_min_before 466448,2021-05-17 12:44:10,45106.51,fair_price_15_min_before 466456,2021-05-17 12:44:15,45122.97,fair_price_15_min_before 466461,2021-05-17 12:44:20,45106.78,fair_price_15_min_before 466466,2021-05-17 12:44:25,45096.55,fair_price_15_min_before 466469,2021-05-17 12:44:30,45088.06,fair_price_15_min_before 466474,2021-05-17 12:44:35,45086.12,fair_price_15_min_before 466491,2021-05-17 12:44:40,45065.95,fair_price_15_min_before 466495,2021-05-17 12:44:45,45068.21,fair_price_15_min_before 466502,2021-05-17 12:44:55,45066.47,fair_price_15_min_before 466506,2021-05-17 12:45:00,45063.82,fair_price_15_min_before 466512,2021-05-17 12:45:05,45070.48,fair_price_15_min_before 466519,2021-05-17 12:45:10,45050.59,fair_price_15_min_before 466523,2021-05-17 12:45:16,45041.13,fair_price_15_min_before 466526,2021-05-17 12:45:20,45038.36,fair_price_15_min_before 466535,2021-05-17 12:45:25,45029.72,fair_price_15_min_before 466553,2021-05-17 12:45:31,45016.2,fair_price_15_min_before 466557,2021-05-17 12:45:35,45011.2,fair_price_15_min_before 466559,2021-05-17 12:45:40,45007.04,fair_price_15_min_before
实现方案
直接用pandas内置的merge_asof方法即可快速实现,该方法是专门为时间序列的就近匹配设计的,比逐行apply的实现效率高几个数量级,代码如下:
import pandas as pd from datetime import timedelta # 读取数据并转换时间列格式 df = pd.read_csv('./data.csv', parse_dates=['date']) # 按时间列升序排序,merge_asof要求关联的时间列有序 df = df.sort_values('date').reset_index(drop=True) # 就近匹配15分钟内的前序行 df_merged = pd.merge_asof( left=df, # 右表只保留需要匹配的时间和价格列 right=df[['date', 'fair_price']], on='date', # 匹配最近的前序行 direction='backward', # 时间差容忍度设为15分钟 tolerance=timedelta(minutes=15), # 列名后缀区分当前值和匹配到的15分钟前的值 suffixes=('', '_15min_ago') ) # 计算差值列 df_merged['fair_price_diff'] = df_merged['fair_price'] - df_merged['fair_price_15min_ago'] # 输出需要的字段 myFields = ['pkey_id', 'date', 'fair_price_15min_ago', 'fair_price', 'fair_price_diff'] print(df_merged[myFields].head(15)) df_merged[myFields].to_csv('output.csv', index=False)
注意事项
- 如果某行前15分钟内没有符合要求的前序行,匹配到的
fair_price_15min_ago会自动为NaN,符合缺失值预期 - 执行前务必确保数据集按
date列升序排序,否则匹配结果会出错
内容的提问来源于stack exchange,提问作者felipe muner
相关产品推荐
相关产品推荐

