亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用-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 關注
  • 256 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號