[英]TypeError: data type 'list' not understood
我有一個 object 系列,由 pandas groupby
返回,其中包含numpy.ndarray
類型的元素。 我想將 ndarrays 轉換為列表,最好不使用循環。 我嘗試使用pandas.Series.astype
但出現錯誤: TypeError: data type 'list' not understood
。 為什么當文檔這么說時
使用 numpy.dtype 或 Python 類型將整個 pandas ZA8CFDE6331BD59EB2AC96F891 轉換為相同的類型。
並且list
是 Python 構建 ID 數據類型。
例子:
a = {'Id': {0: 1, 1: 2, 2: 3},
'col': {0: 5.1, 1: 4.9, 2: 4.9}}
d = pd.DataFrame.from_dict(a)
attr_unique_val = d.groupby('col')['Id'].unique()
attr_unique_val = attr_unique_val.astype('list')
使用您提供的示例,您可以使用 apply 和 lambda:
a = {'Id': {0: 1, 1: 2, 2: 3},
'col': {0: 5.1, 1: 4.9, 2: 4.9}}
d = pd.DataFrame.from_dict(a)
attr_unique_val = d.groupby('col')['Id'].unique()
attr_unique_val = attr_unique_val.apply(lambda x: x.tolist())
如果要將 ndarrays 轉換為列表,則可以使用 tolist() 方法。 例如 - ndarray 名稱是 'narr' 然后你可以寫narr.tolist()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.