大熊猫,长到宽窗

苏妮·安德里亚斯·迪布罗·德贝尔(Sune Andreas Dybro Debel)

我正在尝试通过将行数据的“窗口”转换为列数据来重塑数据框架。例如,给定数据框,窗口大小为2:

    A   B
 0  a1  b1
 1  a2  b2
 2  a3  b3
 3  a4  b4

我想产生数据框:

    A1 A2 B1 B2
 0  a1 a2 b1 b2
 1  a2 a3 b2 b3
 2  a3 a4 b3 b4

这很棘手,因为旧数据帧中的单元格在生成的数据帧中可能没有唯一索引。

我当然可以做一些复杂的事情,例如遍历旧数据框中的行,计算新数据中单元格的位置,然后简单地复制数据。但是我想要一个更简单的解决方案...

YS-L

您可以查看窗口大小为2的操作,方法是将DataFrame向上移动一行,将其与原始DataFrame水平连接,最后进行一些重新排序。因此,无需遍历行就可以这样完成:

res = df.merge(df.shift(-1), left_index=True, right_index=True).iloc[:-1]
res.columns = ['A1', 'B1', 'A2', 'B2']
res = res[['A1', 'A2', 'B1', 'B2']]
print res

输出:

   A1  A2  B1  B2
0  a1  a2  b1  b2
1  a2  a3  b2  b3
2  a3  a4  b3  b4

可以将其概括为任意DataFrame和窗口大小:

def rolling(df, window_size=2):
    dfs = [df]
    for i in range(1, window_size):
        dfs.append(df.shift(-i))
    res = pd.concat(dfs, axis=1).iloc[:-(window_size-1)]
    colnames = [c + str(i) for i in range(1, window_size+1) for c in df.columns]
    reorder = [c + str(i) for c in df.columns for i in range(1, window_size+1)]
    res.columns = colnames
    return res[reorder]

print rolling(df, 3)

输出:

   A1  A2  A3  B1  B2  B3
0  a1  a2  a3  b1  b2  b3
1  a2  a3  a4  b2  b3  b4

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章