【发布时间】: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。
标签: python python-3.x pandas list series