簡體   English   中英

如何將元組列表轉換為 numpy 元組數組?

[英]How convert a list of tupes to a numpy array of tuples?

我有一個這樣的列表:

l=[(1,2),(3,4)]

我想將它轉換為一個 numpy 數組,並將數組項類型保留為元組:

array([(1,2),(3,4)])

但是 numpy.array(l) 會給出:

array([[1,2],[3,4)]])

並且項目類型已從元組更改為 numpy.ndarray,然后我指定了項目類型

numpy.array(l,numpy.dtype('float,float'))

這給出:

 array([(1,2),(3,4)])

但項目類型不是元組而是 numpy.void,所以問題是:

 how to convert it to a numpy.array of tuple,not of numpy.void? 

您可以擁有一個object dtype 數組,讓數組的每個元素都是一個元組,就像這樣 -

out = np.empty(len(l), dtype=object)
out[:] = l

樣品運行 -

In [163]: l = [(1,2),(3,4)]

In [164]: out = np.empty(len(l), dtype=object)

In [165]: out[:] = l

In [172]: out
Out[172]: array([(1, 2), (3, 4)], dtype=object)

In [173]: out[0]
Out[173]: (1, 2)

In [174]: type(out[0])
Out[174]: tuple

出於某種原因,如果您正在尋找一行代碼,則不能簡單地執行此操作(即使 Divakar 的回答最終給您留下了dtype=object ):

np.array([(1,2),(3,4)], dtype=object)

相反,您必須這樣做:

np.array([(1,2),(3,4)], dtype="f,f")

"f,f"向數組發出信號,表明它正在接收兩個浮點數的元組(或者您可以使用"i,i"表示整數)。 如果需要,您可以通過將.astype(object)添加到上面一行的末尾來.astype(object)回對象)。

剛剛發現 pandas 有辦法解決這個問題。 您可以使用他們的MultiIndex類來創建一個元組數組,因為所有 pandas 索引都是包裝的一維 numpy 數組。 這就像在元組列表上調用Index構造函數一樣簡單。

>>> import pandas as pd
>>> tups = [(1, 2), (1, 3)]
>>> tup_array = pd.Index(tups).values
>>> print(type(tup_array), tup_array)
<class 'numpy.ndarray'> [(1, 2) (1, 3)]

暫無
暫無

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

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