如何使用python创建循环移位矩阵

2024-05-20 19:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个循环卷积的代码,现在我被困在需要创建循环移位矩阵的位置上,有人能帮我用python或numpy来做这件事吗

我想循环移动这个矩阵 [1, -1, 2, 0]

我想要矩阵式的

[ 1, -1,  2,  0]
[ 0,  1, -1,  2]
[-2,  0,  1, -1]
[-1, -2,  0,  1]

代码:-

https://drive.google.com/file/d/16XNJ7Q5Iwdlg6Ouz8HU8PgW17xCd1gTp/view?usp=sharing


Tags: 代码httpsnumpycomviewgoogle矩阵drive
2条回答

当按n移位时,取最后的n元素,然后放在列表的前面,即l[len(l)-n:]。剩下的0到len(l)-n-1个元素放在末尾,也就是l[0:len(l)-n]

def shift(l,n):
    return l[len(l)-n:] + l[0:len(l)-n]

output = []
m = [1, -1, 2, 0]
for i in range(4):
    output.append(shift(m, i))
    
print(output)

# [[1, -1, 2, 0], 
#  [0, 1, -1, 2], 
#  [2, 0, 1, -1], 
#  [-1, 2, 0, 1]]

正如在副本中所建议的,collections.deque.rotate(内置库)或numpy.roll(更高效的第三方库)几乎肯定是您想要的

>>> from collections import deque as Deque
>>> d = Deque([1, -1, 2, 0])
>>> d
deque([1, -1, 2, 0])
>>> d.rotate(1)
>>> d
deque([0, 1, -1, 2])
>>> import numpy as np
>>> arr = np.array([1, -1, 2, 0])
>>> np.roll(arr, 1)
array([ 0,  1, -1,  2])
>>> np.roll(arr, 2)
array([ 2,  0,  1, -1])

请注意,deque会对原始集合进行变异,而numpy.roll会返回一个旋转的副本


您可以通过根据数组的长度组合每个可能的卷来创建单个数据帧,尽管您可能会发现在需要时计算卷更有效

>>> arr = np.array([1, 2])
>>> pd.DataFrame([np.roll(arr, roll_index) for roll_index in range(len(arr))])
   0  1
0  1  2
1  2  1
>>> arr = np.array([1, -1, 2, 0, 9])
>>> pd.DataFrame([np.roll(arr, roll_index) for roll_index in range(len(arr))])
   0  1  2  3  4
0  1 -1  2  0  9
1  9  1 -1  2  0
2  0  9  1 -1  2
3  2  0  9  1 -1
4 -1  2  0  9  1

相关问题 更多 >