python - 对数据框进行多次分段分析的最pythonic方法?
问题描述
我在第二个间隔有一个大的时间序列数据帧,我需要对 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
解决方案
IMO,任何包含循环的熊猫解决方案都可以做得更好。
如果没有基本示例,我觉得您的要求可能会让我有些迷茫,但是听起来您正在寻找简单的resample或groupby?
例子
这是一个使用 df 加载的示例,该 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)
返回...
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
此处定义索引中日期时间标志的“分钟”部分。阅读有关偏移别名的更多信息。同样使用该resample()
方法,因为我们的时间序列也充当索引。groupby()
如果我们的日期时间信息不是我们的索引,那么这里也可以采用稍微不同的方法。
定制
lambda()
在应用程序中,您可以使用您希望应用于共享截断日期时间分钟的每个不同的行项目组的任何功能替换 的内容。
推荐阅读
- c++ - 如何在字符串中找到一个字符?
- javascript - 在 Angular 中安装离线 Bootstrap
- pandas - 处理具有不同开始日期的时间序列
- javascript - 未捕获的 ReferenceError: $ 未在 HTML 中定义
- r - R:如何最好地将 %>% 之类的中缀运算符导入我的包中?
- android - Gradle Plugin Update 3.5.0 正在后台销毁活动
- php - 如何在与使用 Google drive API V3 的人共享时设置文件的功能?
- javascript - 如何在没有 Array.prototype.reverse 的情况下在 JavaScript 中反转数组?
- javascript - 如何从 itemlist HTML 中获取价值并在烧瓶中处理
- reactjs - 如何更新使用两个上下文消费者的组件的状态