我有一個需要轉換為 numpy 陣列的串列(變數 len)。例子:
import numpy as np
sample_list = [["hello", "world"], ["foo"], ["alpha", "beta", "gamma"], []]
sample_arr = np.asarray(sample_list)
>>> sample_arr
array([list(['hello', 'world']), list(['foo']),
list(['alpha', 'beta', 'gamma']), list([])], dtype=object)
>>> sample_arr.shape
(4,)
在上面的例子中,我得到了一個所需的一維陣列。代碼的下游模塊期望相同。但是,當串列具有相同的長度時,它會輸出一個二維陣列,導致我的代碼的下游模塊出錯:
sample_list = [["hello"], ["world"], ["foo"], ["bar"]]
sample_arr = np.asarray(sample_list)
>>>
>>> sample_arr
array([['hello'],
['world'],
['foo'],
['bar']], dtype='<U5')
>>> sample_arr.shape
(4, 1)
相反,我想要類似于第一個示例的輸出:
>>> sample_arr
array([list(['hello']), list(['world']),
list(['foo']), list(['bar'])], dtype=object)
有什么辦法可以實作嗎?
uj5u.com熱心網友回復:
您可以通過添加一個虛擬的最后一個子串列將其變成一個鋸齒狀串列,然后將其切掉:
sample_list = [["hello"], ["world"], ["foo"], ["bar"]]
sample_arr = np.asarray(sample_list [[]])[:-1]
輸出:
array([list(['hello']), list(['world']),
list(['foo']), list(['bar'])], dtype=object)
我希望有人能找到一個 hacky 解決方案 :)
uj5u.com熱心網友回復:
一種快速而骯臟的 Pythonic 方法,您可以使用串列理解:
sample_arr = np.asarray([[j] for sub in sample_list for j in sub])
如果您有興趣,可以了解更多關于串列理解的資訊:https : //www.w3schools.com/python/python_lists_comprehension.asp
uj5u.com熱心網友回復:
是的,這是可能的!您可以定義一個函式,將串列串列轉換為包含所有專案的單個串列,如下所示。
import numpy as np
def flatten_list(nested_list):
single_list = []
for item in nested_list:
single_list.extend(item)
return single_list
sample_arr = np.asarray(flatten_list([["hello", "world"], ["foo"], ["alpha", "beta", "gamma"], []]))
print(sample_arr)
uj5u.com熱心網友回復:
在你的第一種情況下,np.array給我們一個警告(在足夠新的 numpy 版本中)。這應該告訴我們一些事情 -np.array用于制作參差不齊的陣列并不理想。 np.array旨在創建具有數字(或字串)dtypes 的常規多維陣列。創建一個像這樣的物件 dtype 陣列是一個后備選項。
In [96]: sample_list = [["hello", "world"], ["foo"], ["alpha", "beta", "gamma"], []]
In [97]: arr = np.array(sample_list)
<ipython-input-97-ec7d58f98892>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
arr = np.array(sample_list)
In [98]: arr
Out[98]:
array([list(['hello', 'world']), list(['foo']),
list(['alpha', 'beta', 'gamma']), list([])], dtype=object)
在許多方面,這樣的陣列是一個貶值的串列,而不是真正的陣列。
在第二種情況下,它可以按預期作業(由開發人員,如果不是你!):
In [99]: sample_list = [["hello"], ["world"], ["foo"], ["bar"]]
In [100]: arr = np.array(sample_list)
In [101]: arr
Out[101]:
array([['hello'],
['world'],
['foo'],
['bar']], dtype='<U5')
為了解決這個問題,我建議創建一個大小合適的物件 dtype 陣列,并從串列中填充它:
In [102]: arr = np.empty(len(sample_list), object)
In [103]: arr
Out[103]: array([None, None, None, None], dtype=object)
In [104]: arr[:] = sample_list
In [105]: arr
Out[105]:
array([list(['hello']), list(['world']), list(['foo']), list(['bar'])],
dtype=object)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330969.html
