将结果存储为大数组的元组

2024-09-29 00:14:47 发布

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

import numpy as np
from scipy import signal

d0 = np.random.random_integers(10, 12, (5,5))
d1 = np.random.random_integers(1, 3, (5,5))
d2 = np.random.random_integers(4, 6, (5,5))
d3 = np.random.random_integers(7, 9, (5,5))
d4 = np.random.random_integers(1, 3, (5,5))
d5 = np.random.random_integers(13, 15, (5,5))

data = np.array([d0,d1,d2,d3,d4,d5])

data = data.reshape(6,25)


data = data.T

想按列计算最小值:

minimas =[]
for x in data:
    minima = (signal.argrelmin(x, axis=0))
    minimas.append(x[minima])

希望以原始数据的形式存储结果。你知道吗

print np.array(minimas).reshape([5,5])

但是

ValueError: total size of new array must be unchanged

难道不能将结果存储为大数组的元组吗? 如果有更有效的方法解决这个问题,我将不胜感激。你知道吗


Tags: integersimportdatasignalnprandomarrayd2
2条回答

您需要将每个项目转换为列表,然后使用列表切片可以索引您需要的任何值。你知道吗

import numpy as np
from scipy import signal

d0 = np.random.random_integers(10, 12, (5, 5))
d1 = np.random.random_integers(1, 3, (5, 5))
d2 = np.random.random_integers(4, 6, (5, 5))
d3 = np.random.random_integers(7, 9, (5, 5))
d4 = np.random.random_integers(1, 3, (5, 5))
d5 = np.random.random_integers(13, 15, (5, 5))

data = np.array([d0, d1, d2, d3, d4, d5])

data = data.reshape(6, 25)

data = data.T

minimas = []
for x in data:
    minima = (signal.argrelmin(x, axis=0))
    minimas.append(x[minima])
tup = list(a.tolist() for a in minimas)
ab = (np.array(tup).reshape(25, 2))
print(ab[0]) #[3 1]

minimas是25个数组的列表(每个形状(2,))。np.array(minimas)具有形状(25,2)。你知道吗

np.array(minimas).reshape(5,5,2)

工作。你知道吗

您可以使用dtype=objectminimas打包到一个数组中:

minarray = np.empty((5,5),dtype=object) # initialize an empty array of 'objects'
minarray[:] = [tuple(m) for m in minimas]
minarray.reshape(5,5)

array([[(1, 2), (1, 1), (2, 2), (2, 2), (3, 3)],
...
       [(3, 2), (1, 2), (1, 1), (1, 2), (2, 3)]], dtype=object)

如果minimas中的数组大小不同,那么该数组将自动具有类型object。你知道吗

minimas[-1] = np.array([1,2,3]) # tweak data so there is some length variation
minimas = [tuple(row) for row in minimas]
np.array(minimas)

产生

array([(1, 2), (1, 1), (2, 2), (2, 2), (3, 3), (2, 1), (3, 2), (3, 3),
       (1, 2), (2, 3), (1, 2), (2, 3), (2, 2), (1, 2), (3, 3), (2, 2),
       (1, 3), (3, 1), (3, 2), (2, 1), (3, 2), (1, 2), (1, 1), (1, 2),
       (1, 2, 3)], dtype=object)  # shape=(25,)

可以是reshape(5,5)。你知道吗

如果minimas中的数组长度相同,则np.array(minimas)生成一个最终大小为2维的数组。这就是为什么我必须初始化所需类型的minarray数组,并在其中插入minimas。这是numpy中一个模糊的部分,我是从回答其他问题中学到的。你知道吗

相关问题 更多 >