创建2d NumPy数组(Python)

时间:2019-02-14 18:05:31

标签: python numpy

NumPy newb。

我在下面的 np_2d 中创建了一个简单的2d数组。效果很好。

当然,我通常需要通过附加和/或连接现有数组来创建N-d数组,因此我将在下一个尝试。

np.append方法(带有或不带有axis参数)似乎没有任何作用。

我尝试使用.concantenate()和/或仅将原始列表替换为np数组的尝试也失败了。

我敢肯定这很简单……对于我的ATM而言,这并非微不足道。有人可以将我推向正确的方向吗? TY。

import numpy as np

# NumPy 2d array:
np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79], [65.4, 59.2, 63.6, 88.4, 68.7]])

print (np_2d) 

# [[ 1.73  1.68  1.71  1.89  1.79]
# [65.4  59.2  63.6  88.4  68.7 ]]

print (np_2d[1]) # second list

# [65.4 59.2 63.6 88.4 68.7]

np_2d_again = np.array([1.1, 2.2, 3.3])

np.append(np_2d_again, [4.4, 5.5, 6.6])
print(np_2d_again)

# wrong: [1.1 2.2 3.3], expect [1.1 2.2 3.3], [4.4, 5.5, 6.6]
# or MAYBE [1.1 2.2 3.3, 4.4, 5.5, 6.6]


np_2d_again = np.array([[1.1, 2.2, 3.3]])
np.concatenate(np_2d_again, np.array([4.4, 5.5, 6.6]))

# Nope: TypeError: only integer scalar arrays can be converted to a scalar index

print(np_2d_again)

np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79])
np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7])

np2_2d_again = np.array(np_height, np_weight)

# Nope: TypeError: data type not understood

height = [1.73, 1.68, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]

np2_2d_again = np.array(height, weight)

# Nope: TypeError: data type not understood

1 个答案:

答案 0 :(得分:2)

对于此类问题,文档可能确实有用。在此处查看它们:

使用这些您会发现:

In [2]: np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79], [65.4, 59.2, 63.6, 88.4, 68.7]])
   ...: 
In [2]: np_2d
Out[2]: 
array([[ 1.73,  1.68,  1.71,  1.89,  1.79],
       [65.4 , 59.2 , 63.6 , 88.4 , 68.7 ]])

请注意np.array的输入。它是一个列表,包含2个相等长度的列表。

In [3]: np_2d_again = np.array([1.1, 2.2, 3.3])
In [4]: np.append(np_2d_again, [4.4, 5.5, 6.6])
Out[4]: array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])

查看np.append文档。看到关于旅行的怎么说?它将一个(3,)数组连接到另一个数组,结果是(6,)。

np.append的名字不好用,经常被滥用。这并不是取代列表追加的原因。一方面,它无法就地运行。

在您的np.concatenate(np_2d_again, np.array([4.4, 5.5, 6.6]))中,您会遇到错误,因为它期望轴号作为第二个参数。重新阅读文档。您需要提供要加入的阵列的列表。 np.append可能误导了。

正确使用concatenate的方式:

In [6]: np.concatenate([np_2d_again, np.array([4.4, 5.5, 6.6])])
Out[6]: array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])

但是由于两个输入均为(3,),所以它们只能在0轴上连接,形成(6,)形状。

np2_2d_again = np.array(np_height, np_weight)有一个类似的问题。第二个参数应该是dtype,而不是另一个数组。您是第一次正确使用np.array

In [7]: np.array([np_2d_again, np.array([4.4, 5.5, 6.6])])
Out[7]: 
array([[1.1, 2.2, 3.3],
       [4.4, 5.5, 6.6]])

np.array沿新轴连接组件。它将数组的列表与原始列表的列表基本相同。

np.stackconcatenate的有用前端,其行为类似于np.array(在使用轴时更具灵活性):

In [8]: np.stack([np_2d_again, np.array([4.4, 5.5, 6.6])])
Out[8]: 
array([[1.1, 2.2, 3.3],
       [4.4, 5.5, 6.6]])
相关问题