TypeError:不理解数据类型“列表”

Posted

技术标签:

【中文标题】TypeError:不理解数据类型“列表”【英文标题】:TypeError: data type 'list' not understood 【发布时间】:2021-07-17 14:49:03 【问题描述】:

我有一个 Series 对象,由 pandas groupby 返回,其中包含 numpy.ndarray 类型的元素。我想将 ndarrays 转换为列表,最好不使用循环。 我尝试使用pandas.Series.astype,但出现错误:TypeError: data type 'list' not understood。为什么documentation这么说

使用 numpy.dtype 或 Python 类型将整个 pandas 对象转换为相同类型。

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')

【问题讨论】:

请在问题中附上您所面临错误的minimal reproducible example。 【参考方案1】:

使用您提供的示例,您可以只使用 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())

【讨论】:

【参考方案2】:

如果你想将 ndarrays 转换为列表,那么你可以使用 tolist() 方法。例如 - ndarray 名称是 'narr' 然后你可以写 narr.tolist()

【讨论】:

是的,但我想一次转换整个系列类型。

以上是关于TypeError:不理解数据类型“列表”的主要内容,如果未能解决你的问题,请参考以下文章