python record.fromarrays错误“;“阵列中的阵列形状不匹配”;

python record.fromarrays错误“;“阵列中的阵列形状不匹配”;,python,arrays,numpy,record,Python,Arrays,Numpy,Record,如果有任何帮助,我将不胜感激:) 我正在尝试从字符串的1d数组创建一个记录数组 和2d数字数组(因此我可以使用np.savetxt并将其转储到文件中)。 不幸的是,这些文档没有提供信息: 如果您只想将x和y转储到CSV文件,那么它就是。但是,如果您有其他原因需要重新排列,以下是如何创建它: import numpy as np import numpy.lib.recfunctions as recfunctions x = np.array(['a', 'b', 'c'], dtype=[(

如果有任何帮助,我将不胜感激:)

我正在尝试从字符串的1d数组创建一个记录数组 和2d数字数组(因此我可以使用np.savetxt并将其转储到文件中)。 不幸的是,这些文档没有提供信息:


如果您只想将
x
y
转储到CSV文件,那么它就是。但是,如果您有其他原因需要重新排列,以下是如何创建它:

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
的输入是一个“数组平面列表”


从数组传递到
的列表中的每个项都将成为结果重新排列的一列。您可以通过检查以下内容来了解这一点:


顺便说一句,您可能想在这里使用它以获得额外的便利(不需要使用数据类型、展开或迭代所需的列):


x
应该是一个数组,对吗?目前它是一个列表。正确,由于某些原因我无法编辑我的帖子…@unutbu答案非常有用!它让我寻找一个更优雅的解决方案来将2d数组与其列分开,我发现了这个:records=np.core.records.fromarrays([x]+[y.transpose()中的行对行])
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
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])])
_array = recarray(shape, descr)

# populate the record array (makes a copy)
for i in range(len(arrayList)):
    _array[_names[i]] = arrayList[i]

return _array
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