如何使用函数创建一个numpy数组? [英] How do I create a numpy array using a function?

查看:99
本文介绍了如何使用函数创建一个numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用np.fromfunction基于函数创建特定大小的数组.看起来像这样:

I am using np.fromfunction to create an array of a specific sized based on a function. It looks like this:

import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(f, (len(test), len(test)), dtype=int)

但是,我收到以下错误消息:

However, I receive the following error:

TypeError: only integer arrays with one element can be converted to an index

推荐答案

该函数需要处理numpy数组.一个简单的方法可以使它工作:

The function needs to handle numpy arrays. An easy way to get this working is:

import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(np.vectorize(f), (len(test), len(test)), dtype=int)

np.vectorize返回f的向量化版本,它将正确处理数组.

np.vectorize returns a vectorized version of f, which will handle the arrays correctly.

这篇关于如何使用函数创建一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆