python - 从一次取 N 个项目的系列中生成矩阵?
问题描述
我被困在一个问题陈述中,其中我有如下所示的数据:-
数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
现在我想生成如下图所示的矩阵。那是有 10 列的矩阵,每行有 10 个先前的值:-
我找不到像这样将序列转换为矩阵的任何最佳或内置方法。任何人都可以帮助我实现这一目标吗?
解决方案
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.]])
它与您的阵列略有不同,但我认为这是您想要的?
推荐阅读
- amazon-web-services - 重定向/忽略 S3 index.html
- html - 低于 768px 的媒体查询不起作用
- angular - 将焦点从输入更改为角度 4 中的 div 并使用箭头键上下滚动内容
- javascript - 使用用户声明的字符串作为方法
- r - “vamin”中的初始值不是有限的
- matlab - matlab如何修改图表坐标轴?
- python - 时间数据 '2017-09-05 18:32:38.159+00' 与格式 '%Y-%m-%d %H:%M:%S.%f%z' 不匹配
- dart - 在 Flutter 中向父 Widget 发送数据
- java - 编舞:跳过33帧!应用程序可能在其主线程上做了太多工作
- entity-framework - SqlException:违反 ****** 约束“******”。无法在对象“******”中插入重复键。重复键值为 ******