创建2d NumPy数组(Python)

2024-09-28 17:22:09 发布

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

纽比新手。在

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

当然,我通常需要通过附加和/或连接现有的数组来创建N-d数组,所以我下一步将尝试这个方法。在

在np.追加方法(有或没有axis参数)似乎什么都不做。在

我尝试使用.concatenate()和/或简单地用np数组替换原始列表也失败了。在

我相信这是微不足道的…只是对我的ATM机来说不是小事。有人能把我推到正确的方向吗?泰。在

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

Tags: 方法datatypenp数组arrayscalarprint
1条回答
网友
1楼 · 发布于 2024-09-28 17:22:09

对于这样的问题,文档可能非常有用。在这里查看:

使用这些,您会发现:

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的输入。它是一个列表,包含两个长度相等的列表。在

^{pr2}$

查看np.append文档。你看这是怎么说的吗?它将一个(3,)数组连接到另一个数组,结果是(6,)。在

np.append名字不好,经常被误用。它不是list 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(在使用axis时更灵活一些):

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

相关问题 更多 >