[英]Create a block numpy array from a numpy array of 2D numpy arrays efficiently
[英]How to create a 2D numpy array from a block of strings
通過列表理解,我可以獲取 20x20 字符串格式的數字塊,並將其轉換為整數列表列表。 數字由空格分隔,行由換行符分隔。
grid = [[int(x) for x in line.split()] for line in nums.split('\n')]
但是,我想要的是使用 numpy 來提高速度。 我可以將 np.asarray() 與我的中間列表一起使用,但我認為這不是對 numpy 的有效使用。
我也嘗試使用np.fromstring()
,但我無法弄清楚使其適用於二維數組的邏輯。
有沒有辦法在不使用創建中間 python 列表的情況下完成這項任務?
您可以使用np.fromstring
將空格設置為分隔符並reshape
為所需的形狀:
np.fromstring(s, sep=' ').reshape(20, 20)
或者作為更通用的解決方案,遵循@mihammad 的解決方案:
rows = s.count('\n') + 1
np.fromstring(s, sep=' ').reshape(-1, rows)
對於任何 2D 網格更通用:
rows = s.count('\n') + 1
np.fromstring(s, sep=' ').reshape(rows, -1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.