使用数据框时,我之前收到一个错误“ 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'
我究竟做错了什么?
pandas.Series.cat.add_categories
它是Series方法,并且df[['embarked', 'sex', 'pclass']]
是DataFrame。pd.Categorical
titanic
数据集列包含NaN
,不能是类别。
.dropna()
在创建类别时使用。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] 删除。
我来说两句