【发布时间】:2019-02-15 03:09:57
【问题描述】:
NumPy 新手。
我在下面的 np_2d 中创建了一个简单的二维数组。效果很好。
当然,我通常需要通过附加和/或连接现有数组来创建 N 维数组,所以接下来我会尝试。
np.append 方法(有或没有轴参数)似乎没有做任何事情。
我尝试使用 .concantenate() 和/或简单地用 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
【问题讨论】:
-
使用
A = np.append(B, C),append函数返回和数组并且不改变参数。 docs.scipy.org/doc/numpy/reference/generated/numpy.append.html -
np.concatenate:“数组必须具有相同的形状”docs.scipy.org/doc/numpy/reference/generated/…(在您的情况下不能连接 2D 和 1D 数组)。 -
远离
np.append;太容易误用了。使用np.concatenate时,请密切注意数组形状。如果重复这样做,最好收集一个列表,并在最后做一个concatenate(或stack)。 -
你到底想用最后一点(身高、体重)达到什么目的?
-
谢谢大家。 @Nathan 没什么,真的。这两个列表可用于计算“最终游戏”中的 BMI,但我真的只是想弄清楚事物的行为(好奇心)与试图解决实际问题的方式