Python pandas - 每第二行而不是每第二个工作日重新采样一次

标签 python pandas resampling datetimeindex

我正在处理股票价格数据,并想让 resample() 每 2 行返回一次,而不是每 2 个工作日返回一次 (resample('2B') ).障碍是在工作日登陆的任何假期。见下文,MLK 日是 2018 年 1 月 15 日,星期一:

import pandas as pd

data = '''\
date,price
2018-01-08,88.28
2018-01-09,88.22
2018-01-10,87.82
2018-01-11,88.08
2018-01-12,89.6
2018-01-16,88.35
2018-01-17,90.14
2018-01-18,90.1
2018-01-19,90.0
2018-01-22,91.61
2018-01-23,91.9
2018-01-24,91.82
2018-01-25,92.33
2018-01-26,94.06'''

fileobj = pd.compat.StringIO(data)
df = pd.read_csv(fileobj, parse_dates=['date'], index_col=[0])

df_resample = df.resample('2B').min()
print(df_resample)

输出:

            price
2018-01-08  88.22
2018-01-10  87.82
2018-01-12  89.60
2018-01-16  88.35
2018-01-18  90.00
2018-01-22  91.61
2018-01-24  91.82
2018-01-26  94.06

我希望重采样从 1/12 跳到 1/17。我知道我可以使用 df['price'].loc[::2] 来传递 df.resample('2B').last() 但我需要也可以使用 min()max()sum()

谢谢。

预期输出:

enter image description here

最佳答案

为了获得稳定的解决方案,我会考虑以某种方式重新定义 B-days。

但是如果你重置索引你可以使用索引号和groupby:

df = df.reset_index()
df_resample = df.groupby(df.index // 2).min()
print(df_resample)

返回:

        date  price
0 2018-01-08  88.22
1 2018-01-10  87.82
2 2018-01-12  88.35
3 2018-01-17  90.10
4 2018-01-19  90.00
5 2018-01-23  91.82
6 2018-01-25  92.33

或者您可以这样做:

g = np.arange(len(df))// 2
df_resample = df.groupby(g).agg(['last','min','max','sum'])
df_resample.insert(0, 'Date', df.index[1::2])

print(df_resample)

返回:

        Date  price                      
               last    min    max     sum
0 2018-01-09  88.22  88.22  88.28  176.50
1 2018-01-11  88.08  87.82  88.08  175.90
2 2018-01-16  88.35  88.35  89.60  177.95
3 2018-01-18  90.10  90.10  90.14  180.24
4 2018-01-22  91.61  90.00  91.61  181.61
5 2018-01-24  91.82  91.82  91.90  183.72
6 2018-01-26  94.06  92.33  94.06  186.39

关于Python pandas - 每第二行而不是每第二个工作日重新采样一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51064030/

相关文章:

python - 使用运行标志减少数据帧

image - 什么是对文本进行下采样的最佳过滤器?

python - 使用 Pandas 创建多个 DataFrame

python - 如何使用 scikit-learn 按标准差标准化数据帧?

python - Pandas 数据框每天重新采样和计数事件

machine-learning - 训练测试拆分后不平衡数据的欠采样

python - 当 PyQt5 应用程序退出时,我得到 "Release of profile requested but WebEnginePage still not deleted. Expect troubles !"

python - 如何使用python从bson日期/时间对象或时间戳获取isodate字符串?

python - Python Pandas 中的 Zip 错误消息 - Anaconda

python - 如何合并多个 pyspark 数组?