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

时间:2019-05-08 00:28:35

标签: python numpy

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

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.]])

输出正是我想要的,我想知道是否有更好的方法来构造这个矩阵?

4 个答案:

答案 0 :(得分:2)

如何使用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.]])

答案 1 :(得分:2)

是否有任何理由不使用此matrix = numpy.array([[1, 1], [2, 1], [3, 2], [numpy.nan, 2]])

答案 2 :(得分:1)

如果有

componentDidMount

您可以执行以下操作:

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

答案 3 :(得分:0)

免责声明:以下方法很可能是最短的方法,但肯定不是最健康的方法。我不会在生产代码中使用它。

np.c_[[2,4,6,np.nan],2:6]//2
# array([[ 1.,  1.],
#        [ 2.,  1.],
#        [ 3.,  2.],
#        [nan,  2.]])
相关问题