为了账号安全,请及时绑定邮箱和手机立即绑定

使用-1为未知行重塑python数组并用None填充剩余空格

使用-1为未知行重塑python数组并用None填充剩余空格

呼啦一阵风 2022-05-11 15:21:10
我有一个长度未知的数组(例如让我们使用 11)。所以数组是[1,2,3,4,5,6,7,8,9,10,11]我想重塑该数组,以便他将拥有 5 列和尽可能多的行。我知道我可以使用reshape(-1,5) 这种方式根据数组长度创建行。但它给了我这个错误:ValueError: cannot reshape array of size 11 into shape (5)知道我该怎么做吗?期望的结果是:[[1,2,3,4,5],[6,7,8,9,10],[11,None,None,None,None]]我运行并收到此错误的代码是:import numpy as npa = np.array([1,2,3,4,5,6,7,8,9,10,11])    print(np.reshape(a, (-1,5)))
查看完整描述

2 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

你可以在没有 numpy 的情况下做到这一点。


ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

n = 5

reshaped = [ar[i: i + n] + [None] * (i + n - len(ar)) for i in range(0, len(ar), n)]

您还可以将技巧与迭代器一起使用(块将在元组中):


reshaped = list(zip(*[iter(ar + [None] * (n - len(ar) % n))] * n))

您可以zip_longest()从 itertools 申请不None自己添加值:


from itertools import zip_longest

reshaped = list(zip_longest(*[iter(ar)] * n))



查看完整回答
反对 回复 2022-05-11
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

In [135]: res = np.empty((3,5), object)                                                                      

In [136]: res                                                                                                

Out[136]: 

array([[None, None, None, None, None],

       [None, None, None, None, None],

       [None, None, None, None, None]], dtype=object)

In [137]: res.flat[:11] = np.arange(1,12)                                                                    

In [138]: res                                                                                                

Out[138]: 

array([[1, 2, 3, 4, 5],

       [6, 7, 8, 9, 10],

       [11, None, None, None, None]], dtype=object)


查看完整回答
反对 回复 2022-05-11
  • 2 回答
  • 0 关注
  • 313 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号