Python 如何将新行添加到空的 numpy 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22392497/
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
How to add a new row to an empty numpy array
提问by Tony Stark
Using standard Python arrays, I can do the following:
使用标准 Python 数组,我可以执行以下操作:
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
# arr is now [[1,2,3],[4,5,6]]
However, I cannot do the same thing in numpy. For example:
但是,我不能在 numpy 中做同样的事情。例如:
arr = np.array([])
arr = np.append(arr, np.array([1,2,3]))
arr = np.append(arr, np.array([4,5,6]))
# arr is now [1,2,3,4,5,6]
I also looked into vstack, but when I use vstackon an empty array, I get:
我也研究了vstack,但是当我vstack在空数组上使用时,我得到:
ValueError: all the input array dimensions except for the concatenation axis must match exactly
So how do I do append a new row to an empty array in numpy?
那么如何将新行附加到 numpy 中的空数组?
采纳答案by askewchan
The way to "start" the array that you want is:
“启动”你想要的数组的方法是:
arr = np.empty((0,3), int)
Which is an empty array but it has the proper dimensionality.
这是一个空数组,但它具有适当的维度。
>>> arr
array([], shape=(0, 3), dtype=int64)
Then be sure to append along axis 0:
然后确保沿轴 0 附加:
arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)
But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:
但是,@jonrsharpe 是对的。事实上,如果你打算在循环中追加,那么在你的第一个例子中追加到一个列表会快得多,然后在最后转换为一个 numpy 数组,因为你真的没有使用 numpy 作为在循环期间打算:
In [210]: %%timeit
.....: l = []
.....: for i in xrange(1000):
.....: l.append([3*i+1,3*i+2,3*i+3])
.....: l = np.asarray(l)
.....:
1000 loops, best of 3: 1.18 ms per loop
In [211]: %%timeit
.....: a = np.empty((0,3), int)
.....: for i in xrange(1000):
.....: a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
.....:
100 loops, best of 3: 18.5 ms per loop
In [214]: np.allclose(a, l)
Out[214]: True
The numpythonic way to do it depends on your application, but it would be more like:
numpythonic 的方法取决于您的应用程序,但它更像是:
In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 μs per loop
In [221]: np.allclose(a, n)
Out[221]: True
回答by mrcl
In this case you might want to use the functions np.hstack and np.vstack
在这种情况下,您可能希望使用函数 np.hstack 和 np.vstack
arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]
arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]
You also can use the np.concatenate function.
您也可以使用 np.concatenate 函数。
Cheers
干杯
回答by boclodoa
using an custom dtype definition, what worked for me was:
使用自定义 dtype 定义,对我有用的是:
import numpy
# define custom dtype
type1 = numpy.dtype([('freq', numpy.float64, 1), ('amplitude', numpy.float64, 1)])
# declare empty array, zero rows but one column
arr = numpy.empty([0,1],dtype=type1)
# store row data, maybe inside a loop
row = numpy.array([(0.0001, 0.002)], dtype=type1)
# append row to the main array
arr = numpy.row_stack((arr, row))
# print values stored in the row 0
print float(arr[0]['freq'])
print float(arr[0]['amplitude'])
回答by just4fun
Here is my solution:
这是我的解决方案:
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)
回答by Rajesh_Saladi
In case of adding new rows for array in loop, Assign the array directly for firsttime in loop instead of initialising an empty array.
如果在循环中为数组添加新行,请直接为循环中的第一次分配数组,而不是初始化一个空数组。
for i in range(0,len(0,100)):
SOMECALCULATEDARRAY = .......
if(i==0):
finalArrayCollection = SOMECALCULATEDARRAY
else:
finalArrayCollection = np.vstack(finalArrayCollection,SOMECALCULATEDARRAY)
This is mainly useful when the shape of the array is unknown
当数组的形状未知时,这主要有用
回答by Qingdong Wang
I want to do a for loop, yet with askewchan's method it does not work well, so I have modified it.
我想做一个for循环,但是askewchan的方法效果不好,所以我修改了它。
x=np.empty((0,3))
y=np.array([1 2 3])
for i in ...
x = vstack((x,y))

