【问题标题】:Insert field into structured array at a specific column index在特定列索引处将字段插入结构化数组
【发布时间】:2014-12-12 15:55:15
【问题描述】:

我目前正在使用np.loadtxt 将一些混合数据加载到结构化的 numpy 数组中。我对一些列进行了一些计算,以便稍后输出。出于兼容性原因,我需要保持特定的输出格式,因此我想在特定点插入这些列并使用np.savetxt 一次性导出数组。

一个简单的设置:

import numpy as np

x = np.zeros((2,),dtype=('i4,f4,a10'))
x[:] = [(1,2.,'Hello'),(2,3.,'World')]

newcol = ['abc','def']

对于这个例子,我想将newcol 设为第二列。我对 Python 很陌生(来自 MATLAB)。从我的搜索中,到目前为止,我能找到的所有方法都是将append newcol to the end of x 设为最后一列,或将x 设为newcol 使其成为第一列。我也找到了np.insert,但它似乎不适用于结构化数组,因为它在技术上是一维数组(据我了解)。

最有效的方法是什么?

编辑1:

我进一步调查了np.savetxt,似乎它不能用于结构化数组,所以我假设我需要循环并用f.write 写入每一行。我可以使用该方法显式指定每一列(按字段名称),而不必担心结构化数组中的顺序,但这似乎不是一个非常通用的解决方案。

对于上面的例子,我想要的输出是:

1, abc, 2.0, Hello
2, def, 3.0, World

【问题讨论】:

  • 当你说“我想让 newcol 成为第二列”是什么意思? x 没有列,它是一维数组对吗?你能告诉我们预期的输出吗?
  • @GiulioGhirardo 当然,看看我的编辑。

标签: python-3.x numpy


【解决方案1】:

这是一种在数组中添加字段的方法,在您需要的位置:

from numpy import zeros, empty


def insert_dtype(x, position, new_dtype, new_column):
    if x.dtype.fields is None:
        raise ValueError, "`x' must be a structured numpy array"
    new_desc = x.dtype.descr
    new_desc.insert(position, new_dtype)
    y = empty(x.shape, dtype=new_desc)
    for name in x.dtype.names:
        y[name] = x[name]
    y[new_dtype[0]] = new_column
    return y


x = zeros((2,), dtype='i4,f4,a10')
x[:] = [(1, 2., 'Hello'), (2, 3., 'World')]

new_dt = ('my_alphabet', '|S3')
new_col = ['abc', 'def']

x = insert_dtype(x, 1, new_dt, new_col)

现在x 看起来像

array([(1, 'abc', 2.0, 'Hello'), (2, 'def', 3.0, 'World')], 
  dtype=[('f0', '<i4'), ('my_alphabet', 'S3'), ('f1', '<f4'), ('f2', 'S10')])

方案改编自here

要将recarray打印到文件中,您可以使用类似的东西:

from matplotlib.mlab import rec2csv
rec2csv(x,'foo.txt')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 2015-11-08
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2017-02-11
    • 2019-11-20
    • 2022-01-25
    相关资源
    最近更新 更多