【问题标题】:How to add two numpy arrays together? [duplicate]如何将两个numpy数组加在一起? [复制]
【发布时间】:2018-12-04 00:11:24
【问题描述】:

在看起来很简单的事情上遇到了一些麻烦。我想加入这两个数组以满足输出:

array([['category_1', '4500', '5000'], ['category_2', '3200', '5000'], ['category_3', '3000', '5000'], ['category_4', '2000', '5000']], dtype='<U8')

我有一些数据

data = np.array([['category_1', '4500', '5000'], ['category_2', '3200', '5000']])

我还有其他数据

other_data = np.array([['category_3', '3000', '5000'], ['category_4', '2000', '5000'])

当我执行此操作时出现此错误

np.concatenate(data, other_data)

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

【问题讨论】:

  • 试试np.concatenate((data, other_data))concatenate 接受一个元组输入。
  • 哇哦,好用!但为什么?但是,元组的定义没有括号。至少我是这么认为的。我可以把 a = 1, 2 和输出将是一个元组
  • 因为这是 NumPy 定义其功能的方式:检查the docs
  • np.concatenate(a, b) 中,a,b 是元组,但它被解包到函数的参数中。 a 对应于函数签名的 (a1,a2...) 参数,ant b 被视为 axis 参数(这就是它抱怨 scalar index 的原因)。 concatenate 不使用 *args 参数。

标签: python arrays numpy multidimensional-array concat


【解决方案1】:
data = np.array([['category_1', '4500', '5000'], ['category_2', '3200', '5000']])
other_data = np.array([['category_3', '3000', '5000'], ['category_4', '2000', '5000']])
np.concatenate((data, other_data), axis=0)

【讨论】:

  • 轴是做什么的?没有它我得到了相同的输出。
  • 轴一般定义,是要垂直添加(列)还是水平添加(行),
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多