想象一下,您有一个结构化的 numpy 数组,它是从 csv 生成的,第一行作为字段名称。该数组具有以下形式:
dtype([('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ..., ('n','<f8'])
现在,假设您想从该数组中删除“第 i 个”列。有没有方便的方法来做到这一点?
我希望它像删除一样工作:
new_array = np.delete(old_array, 'i')
有任何想法吗?
这不是一个单一的函数调用,但以下显示了删除第 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')])
封装为一个函数:
def remove_field_num(a, i):
names = list(a.dtype.names)
new_names = names[:i] + names[i+1:]
b = a[new_names]
return b
删除给定的字段名称可能更自然:
def remove_field_name(a, name):
names = list(a.dtype.names)
if name in names:
names.remove(name)
b = a[names]
return b
另外,查看作为 matplotlib模块一部分的drop_rec_fields
函数。mlab
更新:请参阅我在如何从结构化 numpy 数组中删除列*而不复制它*?用于创建结构化数组的字段子集视图而不制作数组副本的方法。
在这里搜索了我的方式并从 Warren 的回答中了解了我需要知道的内容,我忍不住发布了一个更简洁的版本,并添加了一次有效删除多个字段的选项:
def rmfield( a, *fieldnames_to_remove ):
return a[ [ name for name in a.dtype.names if name not in fieldnames_to_remove ] ]
例子:
a = rmfield(a, 'foo')
a = rmfield(a, 'foo', 'bar') # remove multiple fields at once
或者,如果我们真的要打高尔夫球,以下是等价的:
rmfield=lambda a,*f:a[[n for n in a.dtype.names if n not in f]]