简体   繁体   English

如何将动态生成的值附加到NumPy数组中?

[英]How to append dynamically generated values into NumPy array?

I want to add some dynamically calculated values to result array: 我想向结果数组添加一些动态计算的值:

out = []
for item in foo:
    spam = get_spam(foo)
    out.append(spam)
return np.array(out) 

Unfortunately, this doesn't work, because spam shape is (10,1) and out array has one extra dimension - this is bad. 不幸的是,这是行不通的,因为垃圾邮件的形状为(10,1),并且out数组具有一个额外的维度-这很糟糕。

I did something like this: 我做了这样的事情:

for index, item in enumerate(foo):
    spam = get_spam(foo)
    if index == 0:
        out = spam
    else:
        out = np.append(out, spam, 1)
return out

But this solution is not short, easy, and readable. 但是这种解决方案不是简短,容易且可读的。

How do this in pythonic way? 如何以pythonic方式进行?

You can use numpy concatenate function: 您可以使用numpy concatenate函数:

np.concatenate([get_spam(foo) for item in foo])

It eventually accepts an argument axes for the direction of concatenation (vertically/horizontally). 最终,它接受串联方向(垂直/水平)的自变量

if spam always has the shape (10,1) you could slice the returned array with [:,0] 如果垃圾邮件的形状始终为(10,1),则可以使用[:,0]切片返回的数组

for item in foo:
    spam = get_spam(foo)
    out.append(spam[:,0])
return np.array(out) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM