如何使用函数 numpy.append [英] How to use the function numpy.append
问题描述
我在使用函数 numpy.append 时遇到问题.我编写了以下函数作为较大代码段的一部分,但是,我的错误在以下内容中重现:
I have a problem using the function numpy.append. I wrote the following function as part of a larger piece of code, however, my error is reproduced in the folowing:
data = [
[
'3.5', '3', '0', '0', '15', '6',
'441', 'some text', 'some more complicated data'
],
[
'4.5', '5', '1', '10', '165', '0',
'1', 'some other text', 'some even more complicated data'
]
]
def GetNumpyArrey(self, index):
r = np.array([])
for line in data:
np.append(r, float(line[index]))
print r
索引<6.结果是:
>> []
我做错了什么?
非常感谢!
推荐答案
与 list append
方法不同,numpy 的 append
不会就地追加.它返回一个附加了额外元素的新数组.所以你需要做 r = np.append(r, float(line[index]))
.
Unlike the list append
method, numpy's append
does not append in-place. It returns a new array with the extra elements appended. So you'd need to do r = np.append(r, float(line[index]))
.
不过,以这种方式构建 numpy 数组是低效的.最好将您的列表构建为 Python 列表,然后在最后创建一个 numpy 数组.
Building up numpy arrays in this way is inefficient, though. It's better to just build your list as a Python list and then make a numpy array at the end.
这篇关于如何使用函数 numpy.append的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!