簡體   English   中英

以某種方式將帶有字符串的 3D numpy 數組轉換為 python 列表

[英]Convert a 3D numpy array with strings to a python list in a certain way

考慮以下代碼:

array = np.array2string(np.arange(27).reshape(3,3,3))

這將創建一個具有 3D 維度的 numpy 數組。 output 將如下所示:

[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]

我想將此 numpy 數組轉換為 python 列表,其中每個索引對應於 numpy 數組中的一行。 重要的是要注意每個數字之間有一個空格。 所以 output 看起來像這樣:

    Index Type Size  Value 
    0     str    5   0 1 2 
    1     str    5   3 4 5
    2     str    5   6 7 8 
    3     str    5   9 10 11
....
.... and so on

我將如何編碼?

您可以通過一系列替換來做到這一點:

my_array = np.array2string(np.arange(27).reshape(3,3,3))
# remove brackets
my_array = my_array.replace('[', '').replace(']', '').split('\n')
# remove space at the beginning of each line
my_array = [line.lstrip() for line in my_array]
# keep only strings that are not empty
my_array = [line for line in my_array if line]

結果:

['0  1  2',
 '3  4  5',
 '6  7  8',
 '9 10 11',
 '12 13 14',
 '15 16 17',
 '18 19 20',
 '21 22 23',
 '24 25 26']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM