Numpy append尽管指定了轴,但未添加新行。

huangapple go评论69阅读模式
英文:

Numpy append not adding new row despite axis specification

问题

我是新手使用numpy,我正在尝试添加一行新数据。我看到只需要指定轴。

现在我只是在测试

import numpy as np

arr = np.array(['1', '2', '3'])
print(np.append(arr, np.array(['4', '5', '6']), axis=0))

但这总是输出['1' '2' '3' '4' '5' '6']。我哪里错了?

英文:

I'm new to numpy and I'm trying to create add a new row. I'm reading that I just need to specify the axis.

Right now I'm just testing

import numpy as np

arr = np.array(['1', '2', '3'])
print(np.append(arr, np.array(['4', '5', '6']), axis = 0))

but this always outputs ['1' '2' '3' '4' '5' '6']. Where am I going wrong?

答案1

得分: 5

你的数组只有一个维度(轴),所以你不能将新数据添加到另一个维度。你首先需要重新塑造(reshape):

out = np.append(arr[None], np.array([['4', '5', '6']]), axis=0)

或者:

out = np.append(arr.reshape(1, -1), np.array([['4', '5', '6']]), axis=0)

不过,根据你的用例,vstack 可能更适合:

out = np.vstack([arr, np.array(['4', '5', '6'])])

输出:

array([['1', '2', '3'],
       ['4', '5', '6']], dtype='<U1')
英文:

You array only has one dimension (axis), so you can't add your new data to another dimension. You first need to reshape:

out = np.append(arr[None], np.array([[&#39;4&#39;, &#39;5&#39;, &#39;6&#39;]]), axis=0)

Or:

out = np.append(arr.reshape(1, -1), np.array([[&#39;4&#39;, &#39;5&#39;, &#39;6&#39;]]), axis = 0)

That said, vstack might be better suited to your use-case:

out = np.vstack([arr, np.array([&#39;4&#39;, &#39;5&#39;, &#39;6&#39;])])

Output:

array([[&#39;1&#39;, &#39;2&#39;, &#39;3&#39;],
       [&#39;4&#39;, &#39;5&#39;, &#39;6&#39;]], dtype=&#39;&lt;U1&#39;)

huangapple
  • 本文由 发表于 2023年6月27日 18:58:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定