python variable shape 不匹配_pythonrecord.fromarrays公司错误“数组中的arrayshape不匹配”...

如果您只想将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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值