【发布时间】:2021-03-04 21:04:11
【问题描述】:
我是熊猫新手。我正在使用 pandas 将时间戳记录的 CSV 文件读入数据帧。数据有以下列:
时间戳 COLUMN_A COLUMN_B COLUMN_C
将数据读入数据框后,我希望能够在 COLUMN_C 上运行窗口函数;该函数应返回列的时间戳值。
我写了一些适用于可迭代对象的东西:
import collections
import itertools
def sliding_window_iter(iterable, size):
"""Iterate through iterable using a sliding window of several elements.
Creates an iterable where each element is a tuple of `size`
consecutive elements from `iterable`, advancing by 1 element each
time. For example:
>>> list(sliding_window_iter([1, 2, 3, 4], 2))
[(1, 2), (2, 3), (3, 4)]
"""
iterable = iter(iterable)
window = collections.deque(
itertools.islice(iterable, size-1),
maxlen=size
)
for item in iterable:
window.append(item)
yield tuple(window)
如何修改它以在数据框的列上工作?
【问题讨论】:
-
Pandas 内置了漂亮的comprehensive set of window functions,你检查过你需要的东西是否已经存在了吗?
-
这能回答你的问题吗? Select next N rows in pandas dataframe using iterrows。您仍然需要生成每个连续切片的边界。
-
仅列值?还是操作需要索引?