如何从结构化的numpy数组中删除列? [英] How do you remove a column from a structured numpy array?

查看:120
本文介绍了如何从结构化的numpy数组中删除列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还有一个基本问题,我无法找到答案,但这似乎很容易做到.

I have another basic question, that I haven't been able to find the answer for, but it seems like something that should be easy to do.

好吧,假设您有一个结构化的numpy数组,该数组是从csv生成的,其中第一行为字段名称.数组的形式为:

Ok, imagine you have a structured numpy array, generated from a csv with the first row as field names. The array has the form:

dtype([('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ..., ('n','<f8'])

现在,假设您要从此数组中删除"ith"列.有方便的方法吗?

Now, lets say you want to remove from this array the 'ith' column. Is there a convenient way to do that?

我希望它可以像删除一样工作:

I'd like a it to work like delete:

new_array = np.delete(old_array, 'i')

有什么想法吗?

推荐答案

这不是一个单一的函数调用,但是以下显示了删除第i个字段的一种方法:

It's not quite a single function call, but the following shows one way to drop the i-th field:

In [67]: a
Out[67]: 
array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], 
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

In [68]: i = 1   # Drop the 'B' field

In [69]: names = list(a.dtype.names)

In [70]: names
Out[70]: ['A', 'B', 'C']

In [71]: new_names = names[:i] + names[i+1:]

In [72]: new_names
Out[72]: ['A', 'C']

In [73]: b = a[new_names]

In [74]: b
Out[74]: 
array([(1.0, 3.0), (4.0, 6.0)], 
      dtype=[('A', '<f8'), ('C', '<f8')])

包装为功能

def remove_field_num(a, i):
    names = list(a.dtype.names)
    new_names = names[:i] + names[i+1:]
    b = a[new_names]
    return b

删除给定字段 name

def remove_field_name(a, name):
    names = list(a.dtype.names)
    if name in names:
        names.remove(name)
    b = a[names]
    return b

此外,请查看作为一部分的 drop_rec_fields函数 matplotlib的 mlab模块

Also, check out the drop_rec_fields function that is part of the mlab module of matplotlib.

更新:在

Update: See my answer at How to remove a column from a structured numpy array *without copying it*? for a method to create a view of subsets of the fields of a structured array without making a copy of the array.

这篇关于如何从结构化的numpy数组中删除列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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