嗨,我想在other
之类的条件下将一个分类变量的值更改为['value1','value2']
这是我的代码:
random_sample['NAME_INCOME_TYPE_ind'] = np.where(random_sample['NAME_INCOME_TYPE'] in ['Maternity leave', 'Student']), 'Other')
我尝试在此代码行的不同位置添加.any()
,但仍然无法解决该错误。
ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
答案 0 :(得分:2)
在处理分类时,您可以用其他类别替换,而不是替换字符串。这具有内存和性能上的优势,因为Pandas内部使用分解处理来分类数据。
df = pd.DataFrame({'NAME_INCOME_TYPE': ['Employed', 'Maternity leave',
'Benefits', 'Student']})
# turn object series to categorical
label_col = 'NAME_INCOME_TYPE'
df[label_col] = df[label_col].astype('category')
# define others
others = ['Maternity leave', 'Student']
others_label = 'Other'
# add new category and replace existing categories
df[label_col] = df[label_col].cat.add_categories([others_label])
df[label_col] = df[label_col].replace(others, others_label)
print(df)
NAME_INCOME_TYPE
0 Employed
1 Other
2 Benefits
3 Other
您也可以使用方法链接更简洁地编写此代码:
# define others
others, others_label = ['Maternity leave', 'Student'], 'Other'
# turn to categorical, add category, then replace
df['NAME_INCOME_TYPE'] = df['NAME_INCOME_TYPE'].astype('category')\
.cat.add_categories([others_label])\
.replace(others, others_label)
答案 1 :(得分:1)
您可以使用str.contains
来检查满足条件的地方:
l = ('|').join(['Maternity leave', 'Student'])
m = random_sample['NAME_INCOME_TYPE'].str.contains(l)
您还可以使用.isin
生成m
:
random_sample['NAME_INCOME_TYPE'].isin(['Maternity leave', 'Student'])
然后使用np.where
。但是,请注意,您不能仅指定根据条件从中选择的两个值之一,而必须同时指定x
和y
。对于您的情况,可以将df['NAME_INCOME_TYPE']
和other
用作x
和y
:
random_sample['NAME_INCOME_TYPE_ind'] = np.where(m,
'Other',
random_sample['NAME_INCOME_TYPE'])
在示例数据帧上进行测试:
df = pd.DataFrame({'NAME_INCOME_TYPE':['word1','word2','Student']})
l = ('|').join(['Maternity leave', 'Student'])
m = random_sample['NAME_INCOME_TYPE'].str.contains(l)
df['NAME_INCOME_TYPE_ind'] = np.where(m, 'Other', df['NAME_INCOME_TYPE'])
NAME_INCOME_TYPE NAME_INCOME_TYPE_ind
0 word1 word1
1 word2 word2
2 Student Other