熊猫数据框/ numpy数组-卷不带聚合功能

时间:2019-04-28 14:24:27

标签: python arrays pandas numpy python-3.7

滚动python聚合数据:

x = pd.DataFrame([[1,'a'],[2,'b'],[3,'c'],[4,'d']], columns=['a','b'])
y = x.rolling(2).mean()
print(y)

给予:

     a  b
0  NaN  a
1  1.5  b
2  2.5  c
3  3.5  d

我需要的是3维数据框(或numpy数组),将3个样本按1步移动(在此示例中):

[
  [[1,'a'],[2,'b'],[3,'c']],
  [[2,'b'],[3,'c'],[4,'d']]
]

对于900个样本每步移动1个样本,正确的方法是什么?

4 个答案:

答案 0 :(得分:2)

使用np.concantenate

np.concatenate([x.values[:-1], 
                x.values[1:]], axis=1)\
  .reshape([x.shape[0] - 1, x.shape[1], -1])

答案 1 :(得分:1)

您可以尝试根据所选的窗口长度(选择为2)来串联与窗口长度相关的数据帧

length = df.dropna().shape[0]-1
cols = len(df.columns)
pd.concat([df.shift(1),df],axis=1).dropna().astype(int,errors='ignore').values.reshape((length,cols,2))

出局:

array([[[1, 'a'],
        [2, 'b']],

       [[2, 'b'],
        [3, 'c']],

       [[3, 'c'],
        [4, 'd']]], dtype=object)

答案 2 :(得分:1)

让我知道此解决方案是否适合您的问题。

p = x[['a','b']].values.tolist()  # create a list of list ,as [i.a,i.b] for every i row in x
#### Output  ####
[[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']]


#iterate through list except last two and for every i, fetch p[i],p[i+1],p[i+2] into a list
list_of_3 = [[p[i],p[i+1],p[i+2]] for i in range(len(p)-2)]

#### Output  ####
[
    [[1, 'a'], [2, 'b'], [3, 'c']],
    [[2, 'b'], [3, 'c'], [4, 'd']]
]



# This is used if in case the list you require is numpy ndarray
from numpy import array
a = array(list_of_3)

#### Output  ####
[[['1' 'a']
  ['2' 'b']
  ['3' 'c']]

 [['2' 'b']
  ['3' 'c']
  ['4' 'd']]
]

答案 3 :(得分:1)

自熊猫1.1起,您可以遍历滚动对象:

[window.values.tolist() for window in x.rolling(3) if window.shape[0] == 3]

if确保我们仅获得 full 窗口。该解决方案的优势在于,您可以使用熊猫方便的rolling函数的任何参数。