通过python迭代在numpy/scipy中建立一个数组? [英] Building up an array in numpy/scipy by iteration in Python?
本文介绍了通过python迭代在numpy/scipy中建立一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,我通过迭代一些数据来构建数组,例如:
Often, I am building an array by iterating through some data, e.g.:
my_array = []
for n in range(1000):
# do operation, get value
my_array.append(value)
# cast to array
my_array = array(my_array)
我发现我必须首先构建一个列表,然后将其(使用数组")转换为数组.有没有办法解决这些问题?所有这些强制转换调用使代码变得混乱...如何从头开始以数组形式迭代构建"my_array"?
I find that I have to first build a list and then cast it (using "array") to an array. Is there a way around these? All these casting calls clutter the code... how can I iteratively build up "my_array", with it being an array from the start?
推荐答案
如果我正确理解了您的问题,这应该可以满足您的要求:
If i understand your question correctly, this should do what you want:
# the array passed into your function
ax = NP.random.randint(10, 99, 20).reshape(5, 4)
# just define a function to operate on some data
fnx = lambda x : NP.sum(x)**2
# apply the function directly to the numpy array
new_row = NP.apply_along_axis(func1d=fnx, axis=0, arr=ax)
# 'append' the new values to the original array
new_row = new_row.reshape(1,4)
ax = NP.vstack((ax, new_row))
这篇关于通过python迭代在numpy/scipy中建立一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文