熊猫尝试添加类别值时出现错误“ AttributeError:'DataFrame'对象没有属性'add_categories'”?

Lostsoul:

使用数据框时,我之前收到一个错误“ ValueError:填充值必须在类别中”。经过研究,看来我需要为属于类别的每个值添加分类选项,但出现以下错误:

  catgoricalValues = ['embarked', 'sex', 'pclass']

  df[catgoricalValues] = df[catgoricalValues].astype('category')
  df[catgoricalValues] = df[catgoricalValues].add_categories(df[catgoricalValues].unique())  # add options for catgorical values


AttributeError: 'DataFrame' object has no attribute 'add_categories'

我究竟做错了什么?

特伦顿·麦金尼(Trenton McKinney):

单列

df['embarked'] = pd.Categorical(df['embarked'], categories=df['embarked'].dropna().unique())

多列

# looping through the columns
for col in ['embarked', 'sex', 'pclass']:
    df[col] = pd.Categorical(df[col], categories=df[col].dropna().unique())

# alternatively with .apply
df[['embarked', 'sex', 'pclass']] = df[['embarked', 'sex', 'pclass']].apply(lambda x: pd.Categorical(x, x.dropna().unique(), ordered=True))
# create a sample series
s = pd.Series(["a", "b", "c", "a"], dtype="category")

# add a category
s = s.cat.add_categories([4])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

熊猫-AttributeError:“ DataFrame”对象没有属性“ map”

熊猫:AttributeError:'DataFrame'对象没有属性'agg'

熊猫AttributeError:“ DataFrame”对象没有属性“ Datetime”

AttributeError:“ DataFrame”对象在熊猫中没有属性“ droplevel”

AttributeError: 'DataFrame' 对象在使用 SMOTE 时没有属性 'name'

AttributeError: 'DataFrame' 对象没有属性 'timestamp'

AttributeError:“ DataFrame”对象没有属性“ map”

AttributeError:“ DataFrame”对象没有属性“ label”

AttributeError:“ DataFrame”对象没有属性“ Class”

AttributeError:“ DataFrame”对象没有属性

AttributeError:“ DataFrame”对象没有属性“ dtype”

AttributeError:“ DataFrame”对象没有属性“ Height”

AttributeError:“ DataFrame”对象没有属性“ parse”

Python - AttributeError: 'DataFrame' 对象没有属性

AttributeError: 'DataFrame' 对象没有属性 'save'

AttributeError:尝试从字典列表创建DataFrame时,“ list”对象没有属性“ keys”

大熊猫中的Concat 2列-AttributeError:'DataFrame'对象没有属性'concat'

pandas AttributeError:在groupby上使用apply时,“ DataFrame”对象没有属性“ dt”

AttributeError:将DataFrame保存到xls时,“ NoneType”对象没有属性“ save”

AttributeError:“ QuerySet”对象没有属性“ add”

AttributeError:“模块”对象没有属性“错误”

AttributeError:“元组”对象没有属性“值”

AttributeError: 类型对象“DataFrame”没有属性“pd”

轻松应用:AttributeError:'DataFrame'对象没有属性'name'

AttributeError:“ DataFrame”对象没有属性“ to_datetime”

散景:AttributeError:'DataFrame'对象没有属性'tolist'

AttributeError:“ DataFrame”对象在Python中没有属性“ colmap”

Python AttributeError:“ str”对象没有属性“ DataFrame”

pyspark AttributeError:'DataFrame'对象没有属性'toDF'