如何numpy的recarray的一个子集转换为持续的阵列? [英] How to convert a subset of numpy recarray to continuous array?
问题描述
我有一个 recarray
来自读取csv文件。我感兴趣的列的子集转换成一个连续的float数组。我想,以避免将它们转换为列出或一个堆叠它们。
我试着在 http://stackoverflow.com/a/11792956 并的 http://stackoverflow.com/a/7842620 但我得到
I have a recarray
that comes from reading a csv file. I am interested in converting a subset of columns to a continuous float array. I'd like to avoid converting them to list or stacking them one by one.
I tried the suggestions in http://stackoverflow.com/a/11792956 and http://stackoverflow.com/a/7842620 but I get
ValueError错误:新型阵列与不兼容
ValueError: new type not compatible with array.
下面是我的code:
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')])
转换工作。
推荐答案
numpy的提供的 numpy.ascontiguousarray 。
Numpy provides numpy.ascontiguousarray.
该函数返回其输入数组的内存中的一个连续数组(C顺序)。与阵列非连续的看法时,这是特别有用。
This function returns a contiguous array in memory (C order) of its input array. This is especially helpful when dealing with non contiguous views on arrays.
如果Fortran的订单需要,可以使用<一个href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.asfortranarray.html#numpy.asfortranarray\"相对=nofollow> numpy.asfortranarray 。
If Fortran order is desired, use numpy.asfortranarray.
这篇关于如何numpy的recarray的一个子集转换为持续的阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!