numpy的数组索引 [英] NumPy Array Indexing

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

问题描述

在这里对索引的数组以获取其值的子集简单的问题。说我有一个 recarray 持有在一个空间年龄和相应的值在另一个。我也有一个数组这是我想要的年龄的子集。这里是我的意思是:

Simple question here about indexing an array to get a subset of its values. Say I have a recarray which holds ages in one space, and corresponding values in another. I also have an array which is my desired subset of ages. Here is what I mean:

ages = np.arange(100)
values = np.random.uniform(low=0, high= 1, size = ages.shape)
data = np.core.rec.fromarrays([ages, values], names='ages,values')
desired_ages = np.array([1,4, 16, 29, 80])

我想要做的是这样的:

What I'm trying to do is something like this:

data.values[data.ages==desired_ages]

但是,它不工作。

But, it's not working.

推荐答案

您想创建一个只包含其指标均 desired_ages 。该值的子阵

You want to create an subarray containing only the values whose indexes are in desired_ages.

Python没有直接对应于此的任何语法,但名单COM prehensions可以做pretty不错的工作:

Python doesn't have any syntax that directly corresponds to this, but list comprehensions can do a pretty nice job:

result = [value for index, value in enumerate(data.values) if index in desired_ages]

然而,这样做在Python扫描这样的结果通过 desired_ages 的每个元素在 data.values​​ ,其中是缓慢的。如果你可以插入

However, doing it this way results in Python scanning through desired_ages for each element in data.values, which is slow. If you could insert

desired_ages = set(desired_ages)

这是前行,这会提高性能。 (您可以确定是否在一个值是恒定的一组时间,无论设置的大小)。

on the line before, this would improve performance. (You can determine if a value in is a set in constant time, regardless of the set's size.)

import numpy as np

ages = np.arange(100)
values = np.random.uniform(low=0, high= 1, size = ages.shape)
data = np.core.rec.fromarrays([ages, values], names='ages,values')
desired_ages = np.array([1,4, 16, 29, 80])

result = [value for index, value in enumerate(data.values) if index in desired_ages]
print result

产量

[0.45852624094611272, 0.0099713014816563694, 0.26695859251958864, 0.10143425810157047, 0.93647796171383935]

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

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