python - Pandas 通过滚动行创建新数据框

标签 python pandas dataframe

我正在尝试通过在窗口中滚动行值来创建一个新的 pandas 数据框。即

A   R   N   D   C   Q
-1  -2  -3  -3  -1  -2
-1  -2  -3  -3  -1  -2
-1  -2  -3  -3  -1  -2
-1  -2  -3  -3  -1  -2

像这样:

A1  R1  N1  D1  C1  Q1  A2  R2  N2  D2  C2  Q2  …   An  Rn  Nn  Dn  Cn  Qn
-1  -2  -3  -3  -1  a   -1  -2  -3  -3  -1  b                           
-1  -2  -3  -3  -1  b   -1  -2  -3  -3  -1  c                           
-1  -2  -3  -3  -1  c   -1  -2  -3  -3  -1  d                           
-1  -2  -3  -3  -1  d                                                   
.   .   .   .   .   .                                                   

它类似于字符串中的滚动窗口,即 窗口 3 的 EXAM 将产生 EXA,XAM。这里的主要区别在于,我尝试按行创建窗口,而不是字母。这个新数据框将用于训练支持向量机。虽然我可以创建另一列,其缩放值与其他列相对应(单个列更容易滚动),但我认为我会丢失一些信息,这就是我采用完整列的原因。

本质上,我正在尝试做这样的事情,但是对于 n 窗口大小:

In essence, I'm trying to do something like this, but for n window size

最佳答案

您可以使用 numpy 索引来完成此操作:

In [1]: import pandas as pd
   ...: import numpy as np
   ...: import string
   ...: 

In [2]: abc = list(string.ascii_letters.upper())
   ...: df = pd.DataFrame(dict(a=abc, b=abc[::-1]))
   ...: df.head()
   ...: 
Out[2]: 
   a  b
0  A  Z
1  B  Y
2  C  X
3  D  W
4  E  V

In [3]: # construct a indexing array
   ...: n = 5
   ...: vals = df.values
   ...: idx = np.tile(np.arange(n), (len(df) - n + 1, 1)) + np.arange(len(df) - n + 1).reshape(-1,1)
   ...: idx[:10]
   ...: 
Out[3]: 
array([[ 0,  1,  2,  3,  4],
       [ 1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6],
       [ 3,  4,  5,  6,  7],
       [ 4,  5,  6,  7,  8],
       [ 5,  6,  7,  8,  9],
       [ 6,  7,  8,  9, 10],
       [ 7,  8,  9, 10, 11],
       [ 8,  9, 10, 11, 12],
       [ 9, 10, 11, 12, 13]])

In [4]: # construct columns and index using flattened index array
   ...: cols = [ "{}_{}".format(c,str(i)) for i in range(n) for c in df.columns]
   ...: df2 = pd.DataFrame(vals[idx.flatten()].reshape(len(df)-n+1,df.shape[1]*n), columns=cols)
   ...: df2.head()
   ...: 
Out[4]: 
  a_0 b_0 a_1 b_1 a_2 b_2 a_3 b_3 a_4 b_4
0   A   Z   B   Y   C   X   D   W   E   V
1   B   Y   C   X   D   W   E   V   F   U
2   C   X   D   W   E   V   F   U   G   T
3   D   W   E   V   F   U   G   T   H   S
4   E   V   F   U   G   T   H   S   I   R

关于python - Pandas 通过滚动行创建新数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42751825/

相关文章:

python - 访问 C 初始化的 ctypes 结构元素时出现段错误

python - XmbTextListToTextProperty 结果代码 -2 : error during executing cv2. imshow 来自 shell 脚本的 .py 文件

python-3.x - Unicode解码错误: 'utf-8' codec can't decode byte 0xea in position 23: invalid continuation byte

python - 将函数应用于 pandas 数据帧的每一列而不使用 for 循环?

r - 对于具有 'quadruple nesting' 的多级结构,如何将宽数据帧转换为长数据帧?

python - 在 Python/Pandas/PostgreSQL 中将表名作为函数参数传递

python - 从 pandas Timestamp 获取 MM-DD-YYYY

python - 将多索引与多个列级别和数据框合并

python - 如何从列中删除浮点值 - pandas

r - 如何在R中逐行读取json文件?