如何在Python中索引0维数组? [英] How to index 0-d array in Python?

查看:719
本文介绍了如何在Python中索引0维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一些常见问题解答中存储的一个众所周知的问题,但我无法用Google搜索解决方案.我正在尝试编写标量参数的标量函数,但允许使用ndarray参数.该函数应检查其参数的域正确性,因为域冲突可能会导致异常.此示例演示了我尝试执行的操作:

This may be a well-known question stored in some FAQ but i can't google the solution. I'm trying to write a scalar function of scalar argument but allowing for ndarray argument. The function should check its argument for domain correctness because domain violation may cause an exception. This example demonstrates what I tried to do:

import numpy as np
def f(x):
    x = np.asarray(x)
    y = np.zeros_like(x)
    y[x>0.0] = 1.0/x
    return y

print f(1.0)

在分配y[x>0.0]=...时,python会说0-d arrays can't be indexed. 解决此执行问题的正确方法是什么?

On assigning y[x>0.0]=... python says 0-d arrays can't be indexed. What's the right way to solve this execution?

推荐答案

这在NumPy> = 1.9(在撰写本文时尚未发布)中可以正常使用.在以前的版本中,您可以通过一个额外的np.asarray调用来解决:

This will work fine in NumPy >= 1.9 (not released as of writing this). On previous versions you can work around by an extra np.asarray call:

x[np.asarray(x > 0)] = 0

这篇关于如何在Python中索引0维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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