如果有任何帮助,我将不胜感激:)
我正在尝试从一维字符串数组创建一个记录数组 和二维数字数组(这样我就可以使用 np.savetxt 并将其转储到文件中)。 不幸的是,文档没有提供信息:np.core.records.fromarrays
>>> import numpy as np
>>> x = ['a', 'b', 'c']
>>> y = np.arange(9).reshape((3,3))
>>> print x
['a', 'b', 'c']
>>> print y
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> records = np.core.records.fromarrays([x,y])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/numpy/core/records.py", line 560, in fromarrays
raise ValueError, "array-shape mismatch in array %d" % k
ValueError: array-shape mismatch in array 1
我需要的输出是:
[['a', 0, 1, 2]
['b', 3, 4, 5]
['c', 6, 7, 8]]
请您参考如下方法:
如果您只想将 x 和 y 转储到 CSV 文件,那么它是 not necessary to use a recarray .但是,如果您出于其他原因需要重新排列,可以按照以下方式创建它:
import numpy as np
import numpy.lib.recfunctions as recfunctions
x = np.array(['a', 'b', 'c'], dtype=[('x', '|S1')])
y = np.arange(9).reshape((3,3))
y = y.view([('', y.dtype)]*3)
z = recfunctions.merge_arrays([x, y], flatten=True)
# [('a', 0, 1, 2) ('b', 3, 4, 5) ('c', 6, 7, 8)]
np.savetxt('/tmp/out', z, fmt='%s')
写
a 0 1 2
b 3 4 5
c 6 7 8
到/tmp/out。
或者,要使用 np.core.records.fromarrays,您需要分别列出 y 的每一列,以便将输入传递给 fromarrays 是 the doc says ,一个“数组的平面列表”。
x = ['a', 'b', 'c']
y = np.arange(9).reshape((3,3))
z = np.core.records.fromarrays([x] + [y[:,i] for i in range(y.shape[1])])
传递给 fromarrays 的列表中的每一项都将成为结果 recarray 的一列。您可以通过检查 the source code 看到这一点:
_array = recarray(shape, descr)
# populate the record array (makes a copy)
for i in range(len(arrayList)):
_array[_names[i]] = arrayList[i]
return _array
顺便说一下,你可能想使用 pandas这里是为了额外的方便(不需要处理数据类型、展平或迭代所需的列):
import numpy as np
import pandas as pd
x = ['a', 'b', 'c']
y = np.arange(9).reshape((3,3))
df = pd.DataFrame(y)
df['x'] = x
print(df)
# 0 1 2 x
# 0 0 1 2 a
# 1 3 4 5 b
# 2 6 7 8 c
df.to_csv('/tmp/out')
# ,0,1,2,x
# 0,0,1,2,a
# 1,3,4,5,b
# 2,6,7,8,c
