[英]converting list of lists into 1-D numpy array of lists
我有一個需要轉換為 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)
有什么辦法可以實現嗎?
一種快速而骯臟的 Pythonic 方法,您可以使用列表理解:
sample_arr = np.asarray([[j] for sub in sample_list for j in sub])
如果您有興趣,可以了解更多關於列表理解的信息:https ://www.w3schools.com/python/python_lists_comprehension.asp
您可以通過添加一個虛擬的最后一個子列表將其變成一個鋸齒狀列表,然后將其切掉:
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 解決方案 :)
是的,這是可能的! 您可以定義一個函數,將列表列表轉換為包含所有項目的單個列表,如下所示。
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)
在你的第一種情況下, np.array
給了我們一個警告(在足夠新的 numpy 版本中)。 這應該告訴我們一些事情 - 使用np.array
制作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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.