如果有任何帮助,我将非常感谢:)
我试图从字符串的1d数组创建一个记录数组和2d数组的数字(所以我可以用np。保存并将其转储到文件中)。不幸的是,这些文档没有提供信息: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文件中,那么就没有必要使用重数组。但是,如果您有其他原因需要重新数组,则可以这样创建它:
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
to /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以获得额外的方便(不需要对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