我有一个大小为4的一维空numpy数组(b
),要将列堆叠到其中。列中包含的值取决于另一个包含True / False bool值的1D numpy数组(a
)。
我设法用for循环来填充它,但是我认为可以使用slice来更有效地完成它。
这是可以给我正确结果的工作代码:
import numpy as np
import random
b = np.empty(4, dtype=object) # The array we are trying to fill
for i in range (5):
# a contains 4 random True/False values
a = np.random.randint(0,2,size=(4), dtype=bool)
# If a row is true in a then b should contain data, otherwise nan
data = random.random()
iteration = 0
for value in a :
if b[iteration] is None: # We check if b is empty, if yes we initialize
if (value): # If the row in a is true we fill with the value
b[iteration]=np.array([data])
else:
b[iteration]=np.array([np.nan])
else: # If b is not empty then we just stack
if (value):
b[iteration]=np.hstack([b[iteration],data])
else:
b[iteration]=np.hstack([b[iteration],np.nan])
iteration +=1
print(b)
输出:
array([array([ nan, 0.04209371, 0.03540539, nan, 0.59604905]),
array([0.66677989, nan, 0.03540539, nan, nan]),
array([0.66677989, 0.04209371, 0.03540539, nan, 0.59604905]),
array([0.66677989, 0.04209371, 0.03540539, nan, nan])],
dtype=object)
我已经尝试过使用numpy数组切片的以下代码,但它给了我一个错误:
b = np.empty(4, dtype=object)
for i in range (5):
a = np.random.randint(0,2,size=(4), dtype=bool)
data = random.random()
b[a] = np.vstack([b[a],np.zeros(len(b[a]))+data])
print(b)
输出:
TypeError: NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions
我正在尝试找到解决这个问题的最有效方法,有什么建议吗?
最佳答案
我没有尝试找出您的第二种方法出了什么问题。
从输出中,您首先创建一个4元素数组,其中每个元素都是4元素数组,并随机放置np.nan
。
这是一种直接的二维数组方法,用于生成相同类型的数组:
4x4随机浮动数组:
In [29]: b = np.random.rand(4,4)
In [30]: b
Out[30]:
array([[0.12820464, 0.41477273, 0.35926356, 0.15205777],
[0.28082327, 0.76574665, 0.2489097 , 0.17054426],
[0.20950568, 0.78342284, 0.14498205, 0.52107821],
[0.74684041, 0.83661847, 0.29467814, 0.66062565]])
相同大小的布尔数组:
In [31]: a = np.random.randint(0,2, size=(4,4), dtype=bool)
In [32]: a
Out[32]:
array([[False, True, False, True],
[ True, True, False, True],
[False, False, False, False],
[False, False, True, False]])
使用
a
作为掩码或布尔值索引,将b
的每个对应元素替换为nan
:In [33]: b[a]=np.nan
In [34]: b
Out[34]:
array([[0.12820464, nan, 0.35926356, nan],
[ nan, nan, 0.2489097 , nan],
[0.20950568, 0.78342284, 0.14498205, 0.52107821],
[0.74684041, 0.83661847, nan, 0.66062565]])
这是一个真正的2d浮点数组,而不是数组数组。该对象数组方法适用于列表,但不是质量
numpy
编码。关于python - 根据Python中另一个数组中包含的True/False值填充2D numpy数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48452399/