如何从结构化的numpy.array访问多个字段? [英] How to access multiple fields from a structured numpy.array?

查看:72
本文介绍了如何从结构化的numpy.array访问多个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了访问多个字段(列)的困难

I came across this difficulty accessing multiple fields (columns)

输入:

a = np.array([(1.0, 2,1),(3.0, 4,2),(9, 3,6)], dtype=[('x', float), ('y', float), ('z', float)])
a=np.reshape(a,(a.shape[0],-1))
a

输出:

array([[(1.0, 2.0, 1.0)],
       [(3.0, 4.0, 2.0)],
       [(9.0, 3.0, 6.0)]], 
      dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

如果我想访问第一列,我可以做:

if i want to access the first column i can do:

在:a [:] ['x']

out:array([[1.],[3.],[9.]])

但是如果我想首先访问(例如)第三列,正确的语法是什么?

but what is the right syntax if i want to access (for example) first an 3rd column? Something like

在:a [:] ['x':'z']

显然不起作用

推荐答案

使用字段名称列表作为数组的索引.结果是形状相同的数组,但是记录中只有选定的字段(具有多个字段的数组元素称为记录).

Use a list of field names as an index to the array. The result is an array of the same shape, but with only the selected fields in the records (array elements with multiple fields are called records).

import numpy as np
a = np.array([(1.0, 2,1),(3.0, 4,2),(9, 3,6)], dtype=[('x', float), ('y', float), ('z', float)])
print(a)

print(a[['x', 'z']])

您可以对结果数组应用更高级别的索引,以根据需要选择仅选择所需的元素.

You can apply a further level of indexing to the resulting array to select only the required elements, should you choose.

这篇关于如何从结构化的numpy.array访问多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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