如果您只想将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')
写
^{pr2}$
到/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的列表中的每个项目将成为结果重新排列的一列。您可以通过检查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