我应该如何根据条件将NaN值转换为分类值。尝试转换Nan值时出错。
category gender sub-category title
health&beauty NaN makeup lipbalm
health&beauty women makeup lipstick
NaN NaN NaN lipgloss
我的数据框是这样的。我的功能是把性别中的NaN值转换成分类值
def impute_gender(cols):
category=cols[0]
sub_category=cols[2]
gender=cols[1]
title=cols[3]
if title.str.contains('Lip') and gender.isnull==True:
return 'women'
df[['category','gender','sub_category','title']].apply(impute_gender,axis=1)
如果我运行代码,就会出错
----> 7 if title.str.contains('Lip') and gender.isnull()==True:
8 print(gender)
9
AttributeError: ("'str' object has no attribute 'str'", 'occurred at index category')
如果我们应该使用NaN值,
fillna
可以是以下方法之一:-)或者简单地使用loc作为@COLDSPEED答案的选项3
这里需要注意的是-
apply
是浪费apply
是浪费的,因为它速度很慢,并且不会给您提供矢量化好处.str
对象那样使用pd.Series
访问器。title.contains
就足够了。或者更严重的是,"lip" in title
。gender.isnull
完全错误,gender
是标量,它没有isnull
属性选项1
np.where
不仅速度快,而且简单。如果您担心区分大小写,可以让您的
contains
检查不区分大小写-选项2
另一种方法是使用
pd.Series.mask
/pd.Series.where
-或者
mask
根据提供的掩码隐式地将新值应用于列。相关问题 更多 >
编程相关推荐