类型错误:数据类型“列表”无法理解

问题描述 投票:0回答:3

我有一个 Series 对象,由 pandas

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

使用 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')
python python-3.x pandas list series
3个回答
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())

0
投票

如果你想将 ndarrays 转换为列表,那么你可以使用 tolist() 方法。例如,ndarray 名称是“narr”,那么您可以写

narr.tolist()


0
投票

我也遇到同样的问题,请问你解决了吗

© www.soinside.com 2019 - 2024. All rights reserved.