大多数 pythonic 方法多次对数据帧执行子部分分析?

Most pythonic way to preform sub-section analysis on a data frame multiple times?

我在第二个间隔有一个大的时间序列数据帧,我需要对每个 0-59 秒的分组进行一些分析。 然后通过使用子部分的地板

,将其用作不同时间序列数据帧中的特征

我觉得我缺少一些基本的东西,但不确定措辞是否正确。

例如:

timestamp,close
2021-06-01 00:00:00,37282.0
2021-06-01 00:00:01,37282.0
2021-06-01 00:00:02,37285.0
2021-06-01 00:00:03,37283.0
2021-06-01 00:00:04,37281.0
2021-06-01 00:00:05,37278.0
2021-06-01 00:00:06,37275.0
2021-06-01 00:00:07,37263.0
2021-06-01 00:00:08,37264.0
2021-06-01 00:00:09,37259.0
...
2021-06-01 00:00:59,37260.0
2021-06-02 00:01:00,37261.0 --> new analysis starts here
2021-06-02 00:01:01,37262.0
# and repeat

我当前的实现有效,但我感觉确实是一种糟糕的实现方式。

df['last_update_hxro'] = df.apply(lambda x: 1 if x.timestamp.second == 59 else 0, axis=1)
df['hxro_close'] = df[df['last_update_hxro']==1].close
df['next_hxro_close'] = df['hxro_close'].shift(-60)
df['hxro_result'] = df[df['last_update_hxro']==1].apply(lambda x: 1 if x.next_hxro_close > x.hxro_close else 0, axis=1)
df['trade_number'] = df.last_update_hxro.cumsum() - df.last_update_hxro
unique_trades = df.trade_number.unique()

for x in unique_trades:
    temp_df = btc_df[btc_df['trade_number']==x]
    new_df = generate_sub_min_features(temp_df)
    feature_df = feature_df.append(new_df)

def generate_sub_min_features(full_df):
    # do stuff here and return a series of length 1, with the minute floor of the subsection as the key

首先将时间戳设置为索引:

df['timestamp'] = pd.to_datetime(df['timestamp'], format="%Y-%m-%d %H:%M:S")
df.set_index('timestamp')

然后按小时分组并将每个数据帧保存在列表中:

groups = [g for n, g in df.groupby(pd.Grouper(freq='H'))]

IMO,任何包含循环的 pandas 解决方案都可以做得更好。

如果没有基本示例,我觉得我可能对你的问题有点迷茫,但听起来你正在寻找一个简单的 resample or groupby?

例子

这是一个使用 df 的示例,加载了 1/1/21 - 1/2/21 的不同秒数,与 0 - 10 之间的随机整数配对。我们将取每分钟的平均值。

import pandas as pd
import numpy as np

df_time = pd.DataFrame(
    {'val': np.random.randint(0,10, size=(60 * 60 * 24) + 1)},
    index=pd.date_range('1/1/2021', '1/2/2021', freq='S')
)

df_mean = df_time.resample('T').apply(lambda x: x.mean())

print(df_mean)

Returns...

                          val
2021-01-01 00:00:00  4.566667
2021-01-01 00:01:00  5.000000
2021-01-01 00:02:00  4.316667
2021-01-01 00:03:00  4.800000
2021-01-01 00:04:00  4.533333
...                       ...
2021-01-01 23:56:00  4.916667
2021-01-01 23:57:00  4.450000
2021-01-01 23:58:00  4.883333
2021-01-01 23:59:00  4.316667
2021-01-02 00:00:00  2.000000

备注

请注意此处使用 T 来定义索引中日期时间标志的“分钟”部分。阅读有关 Offset Aliases 的更多信息。还使用 resample() 方法,因为我们的时间序列也充当索引。如果我们的日期时间信息不是我们的索引,groupby() 在这里也可以使用稍微不同的方法。

自定义

在应用程序中,可以将 lambda() 的内容替换为您想要应用于共享截断日期时间分钟的每个不同行项目组的任何函数。