python - 使用 groupby 重新采样 Pandas Dataframe

标签 python pandas dataframe group-by

我在以下形式的 pandas 中有一个数据框:

                       timestap  price    bid    ask  volume
0       2014-06-04 12:11:03.058  21.11  41.12   0.00       0
1       2014-06-04 12:11:03.386  21.17  41.18   0.00       0
2       2014-06-04 12:11:03.435  21.20  41.21   0.00       0
3       2014-06-04 12:11:04.125  21.17  41.19   0.00       0
4       2014-06-04 12:11:04.245  21.16  41.17   0.00       0

我应该做什么:

  1. 用时间戳代替索引
  2. 使用 groupby 重采样时间戳(时间戳应按秒分组)
  3. 在相同的日期和时间显示每列的第一个和最后一个数字

最终的数据框应该是这样的:

                            price           bid         ask    volume
           timestap    min    max    min    max   min   max  min  max
2014-06-04 12:11:03  21.11  21.20  41.12  41.21  0.00  0.00    0    0
2014-06-04 12:11:04  21.16  21.17  41.17  41.19  0.00  0.00    0    0

我现在拥有的:

import pandas as pd
data = pd.read_csv('table.csv')
data.columns = ['timestap', 'bid', 'ask', 'price', 'volume']
data = data.set_index(data.time)
bydate = data.groupby(pd.TimeGrouper(freq='s'))

我的代码出了点问题,我不知道如何完成最后一个任务。你能帮帮我吗?

最佳答案

使用 agg 函数并通过 resamplepd.TimeGrouper 将聚合函数列表传递给它:

# make sure the timestamp column is of date time type
df['timestap'] = pd.to_datetime(df['timestap'])

df.set_index('timestap').resample("s").agg(["min", "max"])

enter image description here

或者使用TimeGrouper:

df.set_index('timestap').groupby(pd.TimeGrouper(freq='s')).agg(['min', 'max'])

关于python - 使用 groupby 重新采样 Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560261/

相关文章:

Python 在(子)函数内传递变量

python - 来自特定 ISO 格式的 Pandas 日期时间转换

python - 查询带有时间戳范围的cassandra表而不使用允许过滤

Python 到 SQL Server 存储过程

python - 从两个日期列中删除月份

python - 如何使用 Pandas 扩展带日期的行

python - 如何从 Datareader pandas 中挑选出单独的数值列?

python - 从数据框创建列表

python - 我如何在数据帧python中找到非时间戳数据?

jquery - 如何从 ajax POST 表单提交中使用 Flask 的 render_template