pandas Python 向数组中添加项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42395193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Add an Item to an Array
提问by Ledger Yu
I have an ndarray that looks like this:
我有一个看起来像这样的 ndarray:
In [1]: a
Out [1]: array(['x','y'], dtype=object)
Now I wanted to append a "z" to the end of it:
现在我想在它的末尾附加一个“z”:
In [2]: print([a,'z'])
[array(['x','y'],dtype=object), 'z']
Instead, what I want is:
相反,我想要的是:
['x','y','z']
Any idea?
任何的想法?
回答by Wenlong Liu
You can do it using numpy.append:
您可以使用numpy.append做到这一点:
import numpy as np
a = np.array(['x','y'])
b = np.append(a,['z'])
In [8]:b
Out[8]: array(['x', 'y', 'z'], dtype='<U1')
回答by Psidom
You can use numpy.append
:
您可以使用numpy.append
:
import numpy as np
a = np.array(['x', 'y'])
np.append(a, 'z')
# array(['x', 'y', 'z'],
# dtype='<U1')
回答by armatita
As alternative to append(since you can use it for several iterables; check for example: PEP3132) you can use the "unpacking" symbol to do it:
作为附加的替代方法(因为您可以将它用于多个可迭代对象;检查例如:PEP3132)您可以使用“解包”符号来执行此操作:
import numpy as np
a = np.array(['x','y'], dtype=object)
b = np.array([*a, "z"])
print(*a, "z")
print(b)
The result is this:
结果是这样的:
x y z
['x' 'y' 'z']