【问题标题】:Why does pandas categorical DataFrame give truth value error?为什么 pandas categorical DataFrame 会给出真值错误?
【发布时间】:2018-01-02 14:30:52
【问题描述】:

我的数据包含一列“已婚”,其分类值为是或否。我将其更改为数字类型:

 train['Married']=train['Married'].astype('category')
 train['Married'].cat.categories=[0,1]

现在我正在使用以下代码来填充缺失值:

train['Married']=train['Married'].fillna(train['Married'].mode())

它给出了错误:

 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

谁能解释一下原因?

【问题讨论】:

  • 您能否分解计算以查看此错误是否是由于.mode().fillna()= 属性造成的?

标签: python pandas machine-learning scikit-learn


【解决方案1】:

错误表明您在 numpy 数组或 pandas 系列上使用基础 python 中的 not, and, or 等逻辑运算符:

例如:

s = pd.Series([1,1,2,2])
not pd.isnull(s.mode())

给出同样的错误:

ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

如果你查看堆栈跟踪,错误来自这一行:

fillna(self, value, method, limit)
   1465         else:
   1466 
-> 1467             if not isnull(value) and value not in self.categories:
   1468                 raise ValueError("fill value must be in categories")
   1469 

所以它正在检查您尝试填写的值是否在类别中;并且此行要求该值是标量,以便与notand 兼容;然而,series.mode() 总是返回一个系列,这行失败,尝试从 mode() 中提取值并填充它:

train['Married']=train['Married'].fillna(train['Married'].mode().iloc[0])

一个工作示例:

s = pd.Series(["YES", "NO", "YES", "YES", None])    
s1 = s.astype('category')
s1.cat.categories = [0, 1]

s1
#0    1.0
#1    0.0
#2    1.0
#3    1.0
#4    NaN
#dtype: category
#Categories (2, int64): [0, 1]

s1.fillna(s1.mode().iloc[0])
#0    1
#1    0
#2    1
#3    1
#4    1
#dtype: category
#Categories (2, int64): [0, 1]

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 2018-12-10
    • 2016-01-23
    • 2013-07-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多