首页 > 解决方案 > 从一次取 N 个项目的系列中生成矩阵?

问题描述

我被困在一个问题陈述中,其中我有如下所示的数据:-

数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

现在我想生成如下图所示的矩阵。那是有 10 列的矩阵,每行有 10 个先前的值:-

在此处输入图像描述

我找不到像这样将序列转换为矩阵的任何最佳或内置方法。任何人都可以帮助我实现这一目标吗?

标签: pythonpandasmatrix

解决方案


import numpy as np

zeros = np.zeros((20,10))
numbers = np.arange(1,21)
for index, value in enumerate(numbers):
    if index < 10:
        arr = np.pad(numbers[:index],(0, 10-index), mode='constant')
    else:
        arr = numbers[index-10:index]
    zeros[index] = arr
print(numbers)

这给出了:

zeros...
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  2.,  3.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  2.,  3.,  4.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  6.,  0.,  0.,  0.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  0.,  0.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  0.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.,  0.],
       [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.],
       [ 2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.],
       [ 3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.],
       [ 4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12., 13.],
       [ 5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14.],
       [ 6.,  7.,  8.,  9., 10., 11., 12., 13., 14., 15.],
       [ 7.,  8.,  9., 10., 11., 12., 13., 14., 15., 16.],
       [ 8.,  9., 10., 11., 12., 13., 14., 15., 16., 17.],
       [ 9., 10., 11., 12., 13., 14., 15., 16., 17., 18.],
       [10., 11., 12., 13., 14., 15., 16., 17., 18., 19.]])

它与您的阵列略有不同,但我认为这是您想要的?


推荐阅读