[英]How do you remove a column from a structured numpy array?
Imagine you have a structured numpy array, generated from a csv with the first row as field names.假设您有一个结构化的 numpy 数组,它是从 csv 生成的,第一行作为字段名称。 The array has the form:
该数组具有以下形式:
dtype([('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ..., ('n','<f8'])
Now, lets say you want to remove from this array the 'ith' column.现在,假设您要从此数组中删除 'ith' 列。 Is there a convenient way to do that?
有没有方便的方法来做到这一点?
I'd like a it to work like delete:我希望它像删除一样工作:
new_array = np.delete(old_array, 'i')
Any ideas?有任何想法吗?
It's not quite a single function call, but the following shows one way to drop the i-th field:这不是一个单一的函数调用,但以下显示了删除第 i 个字段的一种方法:
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')])
Wrapped up as a function:总结为一个函数:
def remove_field_num(a, i):
names = list(a.dtype.names)
new_names = names[:i] + names[i+1:]
b = a[new_names]
return b
It might be more natural to remove a given field name :删除给定的字段名称可能更自然:
def remove_field_name(a, name):
names = list(a.dtype.names)
if name in names:
names.remove(name)
b = a[names]
return b
Also, check out the drop_rec_fields
function that is part of the mlab
module of matplotlib.另外,请查看属于 matplotlib 的
mlab
模块的drop_rec_fields
函数。
Update : See my answer at How to remove a column from a structured numpy array *without copying it*?更新:请参阅我在如何从结构化的 numpy 数组中删除列 * 而不复制它* 的答案? for a method to create a view of subsets of the fields of a structured array without making a copy of the array.
用于创建结构化数组字段子集视图而不复制数组的方法。
Having googled my way here and learned what I needed to know from Warren's answer, I couldn't resist posting a more succinct version, with the added option to remove multiple fields efficiently in one go:在这里搜索了我的方式并从 Warren 的回答中了解了我需要知道的内容后,我忍不住发布了一个更简洁的版本,并添加了一次有效删除多个字段的选项:
def rmfield( a, *fieldnames_to_remove ):
return a[ [ name for name in a.dtype.names if name not in fieldnames_to_remove ] ]
Examples:例子:
a = rmfield(a, 'foo')
a = rmfield(a, 'foo', 'bar') # remove multiple fields at once
Or if we're really going to golf it, the following is equivalent:或者,如果我们真的要打高尔夫球,下面是等价的:
rmfield=lambda a,*f:a[[n for n in a.dtype.names if n not in f]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.