python - 通过滚动窗口在 Pandas 中高效地从多行创建宽表

标签 python pandas numpy

我有一个 600 列的数据框,大约有 1,000,000 行。所有单元格都是 float32。

我需要在数据帧中按行移动滚动窗口(长度为 30),以创建一个新行来组合窗口中的行。这将是 600 * 30 == 18000宽度约为1,000,000 - 30长度(行)。由于滚动窗口,原始数据帧中的行在结果中重复(根据设计)。

下面是一些粗略的(未经测试的)代码来总结需求。实际上我会分配一个正确长度的 numpy 数组而不是 Xy_hist = [] python 列表。

# tmp is the large df already defined
total_size = tmp.shape[0]
window_size = 30
Xy_hist = []
for x in range(total_size-window_size):
    tmp_df = tmp.iloc[0+x:window_size+x,:].stack().to_frame().T
    tmp_df.columns = tmp_df.columns.get_level_values(1)
    Xy_hist.append(tmp_df)
res = pd.concat(Xy_hist)

我认为这种方法的内存效率非常低,而且计算效率也可能很低。有没有更好的Pythonic和/或Pandas native 方法来解决这个问题?

最佳答案

我不确定这是否正是您所需要的,只是我的靶心解决方案,您可以这样做:

total_size = tmp.shape[0]
window_size = 30
res = pd.concat([tmp.iloc[x:window_size+x,:] for x in range(0, total_size, window_size)])

关于python - 通过滚动窗口在 Pandas 中高效地从多行创建宽表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53968618/

相关文章:

Python 套接字发送缓冲区与。强度

python - Pandas:将行附加到列中具有多索引的DataFrame

python - pandas dataframe 按 nan 数删除列

python - np.where(condition is None) 不等于 np.where(condition == None)

python - 在python中,如何使正确的操作数在乘以两个不同的类时优先( __rmul__ 方法)?

python - pandas, numpy 四舍五入到最接近的 100

python - 按小时对 Pandas 数据框进行分组的问题

python - Pandas - 比较数据框中的 2 列并返回计数

numpy.VisibleDeprecationWarning : Creating an ndarray from ragged nested sequences

python - 为什么 Ruby 比 Python 更适合 Rails?