【问题标题】:python record.fromarrays error "array-shape mismatch in array"python record.fromarrays 错误“数组中的数组形状不匹配”
【发布时间】:2014-05-15 21:31:42
【问题描述】:

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

我正在尝试从一维字符串数组创建一个记录数组 和二维数字数组(所以我可以使用 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 应该是一个数组,对吧?目前它是一个列表。
  • 正确,由于某种原因我无法编辑我的帖子...
  • @unutbu 的回答很有帮助!它让我寻找一种更优雅的解决方案来将二维数组与其列分开,我发现了这个:records = np.core.records.fromarrays([x]+[row for row in y.transpose()])

标签: python arrays numpy record


【解决方案1】:

如果您只想将xy 转储到一个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 以获得额外的便利(无需使用 dtypes、展平或迭代所需的列):

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

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2016-07-21
    • 1970-01-01
    • 2019-12-10
    • 2021-01-09
    • 1970-01-01
    • 2021-07-14
    • 2015-11-06
    • 1970-01-01
    相关资源
    最近更新 更多