英文:
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([['4', '5', '6']]), axis=0)
Or:
out = np.append(arr.reshape(1, -1), np.array([['4', '5', '6']]), axis = 0)
That said, vstack
might be better suited to your use-case:
out = np.vstack([arr, np.array(['4', '5', '6'])])
Output:
array([['1', '2', '3'],
['4', '5', '6']], dtype='<U1')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论