【问题标题】:How to convert a subset of numpy recarray to continuous array?如何将 numpy recarray 的子集转换为连续数组?
【发布时间】:2015-06-20 04:05:09
【问题描述】:

我有一个来自读取 csv 文件的recarray。我有兴趣将列的子集转换为连续的浮点数组。我想避免将它们转换为列表或将它们一一堆叠。 我尝试了https://stackoverflow.com/a/11792956https://stackoverflow.com/a/7842620 中的建议,但我得到了

ValueError: 新类型与数组不兼容。

这是我的代码:

a = np.recfromcsv(r"myfile.csv")
#a has many columns of type int, float or string. I want to extract those called coeff*
coeffs_columns = [n for n in a.dtype.names if n.startswith('coeff')] 
coeffs_recarray = a[coeffs_columns]
newtype=[(n,'<f8') for n in coeffs_columns]
b = coeffs_recarray.astype(newtype)
#b is:
#array((0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),  dtype=[('coefficients00', '<f8'), ('coefficients1', '<f8'), ('coefficients2', '<f8'), ('coefficients3', '<f8'), ('coefficients4', '<f8'), ('coefficients5', '<f8'), ('coefficients6', '<f8'), ('coefficients7', '<f8'), ('coefficients8', '<f8'), ('coefficients9', '<f8'), ('coefficients100', '<f8'), ('coefficients11', '<f8'), ('coefficients12', '<f8'), ('coefficients13', '<f8'), ('coefficients14', '<f8')])
coeffs = b.view('<f8')

“有趣”的是,如果我只提取一列,或者如果我使用 recarray 创建为

x = np.array([(1.0, 2,7.0), (3.0, 4, 9.9)], 
                 dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

转换有效。

【问题讨论】:

  • 您是否尝试过np.ascontiguousarray 对您感兴趣的数组?
  • a[coeffs_columns].view('f') 工作吗?
  • @hpaulj 不,它给出了相同的结果
  • @Bort,谢谢,这已经解决了问题!如果您将其转换为答案,我会接受它
  • 另一个“有趣”的事情是 coeffs_recarray.flags['C_CONTIGUOUS'] 是 True ,但它只有在我明确使用 np.ascontguousarray 时才有效

标签: python arrays python-2.7 numpy recarray


【解决方案1】:

Numpy 提供numpy.ascontiguousarray

此函数在其输入数组的内存(C 顺序)中返回一个连续数组。这在处理数组上的非连续视图时特别有用。

如果需要 Fortran 顺序,请使用 numpy.asfortranarray

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 1970-01-01
    • 2011-01-29
    • 2013-07-14
    • 1970-01-01
    • 2022-06-13
    • 2020-01-10
    相关资源
    最近更新 更多