Python:如何通过对相邻单元格求和来重塑数据框?

时间:2019-03-21 13:58:41

标签: python pandas numpy group-by

我已经从矩阵生成了数据帧df

M=np.random.randint(10, size=(7, 5))
df = pd.DataFrame(M)
df  
        0   1   2   3   4
     0  8   3   2   2   5
     1  5   8   1   5   6
     2  1   9   1   4   2
     3  0   7   7   6   9
     4  5   8   7   0   9
     5  0   3   9   9   4
     6  7   7   8   5   4

我想通过对df1的相邻单元格3x3求和来生成一个新的数据帧df

### Aggregate rows 0,1,2 and columns 0,1,2
df1[0][0] = [8+3+2+5+8+1+1+9+1] = 38
### Aggregate rows 0,1,2 and columns 2,3,4
df1[1][0] = [2+2+5+1+5+6+1+4+2] = 28

### Aggregate rows 2,3,4 and columns 0,1,2
df1[1][0] = [1+9+1+0+7+7+5+8+7] = 45
### Aggregate rows 2,3,4 and columns 2,3,4
df1[1][1] = [1+4+2+7+6+9+7+0+9] = 45

### Aggregate rows 4,5,6 and columns 0,1,2
df1[2][0] = [5+8+7+0+3+9+7+7+8] = 55
### Aggregate rows 4,5,6 and columns 2,3,4
df1[2][1] = [7+0+9+9+9+4+8+5+4] = 55


df1    
        0    1
    0  38   28
    1  45   45
    2  55   55

2 个答案:

答案 0 :(得分:2)

您可以在scipy中使用带有convolve2d函数的卷积来完成此操作:

M = np.random.randint(10, size=(7, 5))
print(M)

[[9 2 4 5 8]
 [4 0 3 4 9]
 [9 4 6 3 0]
 [4 6 9 9 5]
 [4 3 1 3 9]
 [9 2 9 0 7]
 [4 3 7 6 1]]


from scipy.signal import convolve2d

r = convolve2d(M, np.ones([3,3]), mode='same')[1::2,1::2]
print(r)

[[41. 42.]
 [46. 45.]
 [42. 43.]]

这里np.ones([3,3])生成3x3的1的掩码:

array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

我正在使用[1 :: 2,1 :: 2]索引从元素1而不是0开始,并像问题中那样跳过其他所有行/列。

另请参见Getting sum of adjacent elements of a matrix

答案 1 :(得分:0)

您可以使用df.shift

axes = (0, 1)
shifts = -1, 1
intermediate_sum = (
    df
    + sum(df.shift(shift, axis=axis) for shift, axis in product(shifts, axes))
)
result = (
    intermediate_sum.dropna(how="all", axis=0)
    .dropna(how="all", axis=1)
    .iloc[::2, ::2]
)
result
  1   3
1 23.0    22.0
3 35.0    33.0
5 18.0    18.0