【问题标题】:TypeError: data type 'list' not understoodTypeError:不理解数据类型“列表”
【发布时间】: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')

【问题讨论】:

标签: python python-3.x pandas list series


【解决方案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()

    【讨论】:

    • 是的,但我想一次转换整个系列类型。
    猜你喜欢
    • 2020-06-16
    • 2018-05-24
    • 2021-06-11
    • 2020-03-25
    • 2018-12-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多