gpt4 book ai didi

python - 传递 dtype= 'category' 的系列作为 Pandas 分类函数的类别

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:53 26 4
gpt4 key购买 nike

当我运行这段代码时,出现以下错误:

import pandas as pd

car_colors = pd.Series(['Blue', 'Red', 'Green'],
dtype='category')

car_data = pd.Categorical(['Yellow', 'Green', 'Red', 'Blue','Purple'],
categories= car_colors, ordered=False)
print car_colors
s = pd.Series(car_data)
s

ValueError: object array method not producing an array

但有趣的是,当我删除 dtype = 'category' 时,代码工作正常。

简而言之,分类函数接受系列但不接受 dtype = 'category'

这是错误还是我做错了什么?

最佳答案

看起来需要将 tolist 添加到 Categorical 中的 categories :

car_colors = pd.Series(['Blue', 'Red', 'Green'],
dtype='category')

car_data = pd.Categorical(['Yellow', 'Green', 'Red', 'Blue','Purple'],
categories = car_colors.tolist(), ordered=False)

s = pd.Series(car_data)
print (s)

0 NaN
1 Green
2 Red
3 Blue
4 NaN
dtype: category
Categories (3, object): [Blue, Red, Green]

来自 EdChum's comment 的另一个解决方案正在使用cat.categories :

car_data = pd.Categorical(['Yellow', 'Green', 'Red', 'Blue','Purple'],
categories = car_colors.cat.categories, ordered=False)
s = pd.Series(car_data)
print (s)
0 NaN
1 Green
2 Red
3 Blue
4 NaN
dtype: category
Categories (3, object): [Blue, Green, Red]

关于python - 传递 dtype= 'category' 的系列作为 Pandas 分类函数的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39467885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com