[英]TypeError: data type 'list' not understood
I have a Series object, returned by pandas groupby
, which has elements of numpy.ndarray
type.我有一个 object 系列,由 pandas
groupby
返回,其中包含numpy.ndarray
类型的元素。 I would like to convert ndarrays to lists, preferably without using loops.我想将 ndarrays 转换为列表,最好不使用循环。 I tried to use
pandas.Series.astype
but I got error: TypeError: data type 'list' not understood
.我尝试使用
pandas.Series.astype
但出现错误: TypeError: data type 'list' not understood
。 Why is that when documentation says that为什么当文档这么说时
Use a numpy.dtype or Python type to cast entire pandas object to the same type.
使用 numpy.dtype 或 Python 类型将整个 pandas ZA8CFDE6331BD59EB2AC96F891 转换为相同的类型。
and list
is Python buil-id data type.并且
list
是 Python 构建 ID 数据类型。
Example:例子:
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')
You can just use apply and lambda, using the example you provided:使用您提供的示例,您可以使用 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())
If you want to convert ndarrays to list then you can use tolist() method.如果要将 ndarrays 转换为列表,则可以使用 tolist() 方法。 For example- the ndarray name is 'narr' then you can write
narr.tolist()
.例如 - ndarray 名称是 'narr' 然后你可以写
narr.tolist()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.