python record.fromarrays 错误 "数组形状不匹配

2 投票
1 回答
2192 浏览
提问于 2025-04-18 06:43

我非常感谢任何帮助 :)

我想从一个一维的字符串数组和一个二维的数字数组创建一个记录数组,这样我就可以使用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]]

1 个回答

2

如果你只是想把 xy 保存到一个 CSV 文件里,那么其实不需要使用 recarray。如果你有其他原因想用 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 的输入就像文档里说的,是一个“扁平的数组列表”。

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 的一列。你可以通过查看 源代码来验证这一点:

_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

撰写回答