有没有更好的方法来构造一个具有特定值的特定矩阵?

2024-04-28 04:16:57 发布

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

我用这段代码构造了一个矩阵

c_bed = np.append(np.array([1, 2, 3]), np.nan).reshape(4, 1)
c_bath = np.array([1, 1, 2, 2], dtype=np.float).reshape(4, 1)
ds = np.append(c_bed, c_bath, axis=1)

这给了

array([[ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  2.],
       [nan,  2.]])

输出正是我想要的,我想知道有没有更好的方法来构建这个矩阵?你知道吗


Tags: 方法代码npds矩阵nanfloatarray
3条回答

zip_longest怎么样

from itertools import zip_longest
np.array(list(zip_longest([1,2,3],[1,1,2,2],fillvalue=np.nan)))
Out[228]: 
array([[ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  2.],
       [nan,  2.]])

如果你有

beds = [1, 2, 3]
baths = [1, 1, 2, 2]
data = (beds, baths)

您可以执行以下操作:

ds = np.full((max(map(len, data)), 2), np.nan)
ds[:len(beds), 0] = beds
ds[:len(baths), 1] = baths

有什么理由不使用这个matrix = numpy.array([[1, 1], [2, 1], [3, 2], [numpy.nan, 2]])?你知道吗

相关问题 更多 >