簡體   English   中英

將多維numpy數組轉換為字符串列表

[英]convert multidimensional numpy array to list of string

我有一個numpy的數組:

x = np.array([[1.5,1.3],[2.5,1.5]])

將其轉換為類似這樣的字符串列表的最Python方式是什么:

y = ['1.5 1.3','2.5 1.5']

我現在做的不是很有效:

y = []
for i in range(x.shape[0]):
    txt = ''
    for j in range(x.shape[1]):
       txt+=' '%.5e'%x[i,j]
    y.append(txt)

嘗試過:

x = x.astype('|S10').tolist()
y = [' '.join(i) for i in x]

但是如果x中有很多小數位,它將在第10個小數位后截斷。

您可以簡單地使用列表理解:

>>> x = np.array([[1.5,1.3],[2.5,1.5]])
>>> y = [' '.join('{:.5e}'.format(col) for col in line) for line in x]
>>> y 
['1.50000e+00 1.30000e+00', '2.50000e+00 1.50000e+00']

您可以將'{:.5}'更改為所需的任何格式。

這是一種方法,首先使用.astype('S4')轉換將輸入數字數組轉換為字符串數組,然后執行一級循環理解,以使用" ".join(item)連接每一行中的所有字符串,其中item是字符串數組中的每一行,就像這樣-

[" ".join(item) for item in x.astype('S4')]

如果您正在尋找精度控制,則可以將dtype更改為S6S12S14

樣品運行-

In [9]: x
Out[9]: 
array([[ 0.62047293,  0.02957529,  0.88920602,  0.57581068],
       [ 0.40903378,  0.80748886,  0.83018903,  0.22445871],
       [ 0.87296866,  0.94234112,  0.70001789,  0.99333763],
       [ 0.96689113,  0.35128491,  0.35775966,  0.26734985]])

In [10]: [" ".join(item) for item in x.astype('S4')]
Out[10]: 
['0.62 0.02 0.88 0.57',
 '0.40 0.80 0.83 0.22',
 '0.87 0.94 0.70 0.99',
 '0.96 0.35 0.35 0.26']

In [11]: [" ".join(item) for item in x.astype('S14')]
Out[11]: 
['0.620472934011 0.029575285327 0.889206021736 0.575810682998',
 '0.409033783485 0.807488858152 0.830189034897 0.224458707937',
 '0.872968659668 0.942341118836 0.700017893576 0.993337626766',
 '0.966891127767 0.351284905075 0.357759658063 0.267349854182']

暫無
暫無

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

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