【发布时间】:2021-02-24 15:18:03
【问题描述】:
我有一个类似的数据集:
Mother ID ChildID ethnicity
0 1 1 White Other
1 2 2 Indian
2 3 3 Black
3 4 4 Other
4 4 5 Other
5 5 6 Mixed-White and Black
为了简化我的数据集并使其与我正在执行的分类更加相关,我想将种族分为 3 类:
- 白人:在此类别中,我将包括“英国白人”和“其他白人”价值观
- 南亚:该类别将包括“巴基斯坦”、“印度”、“孟加拉国”
- 其他:“其他”、“黑色”、“混合白色和黑色”、“混合白色和南亚”值
所以我希望将上面的数据集转换为:
Mother ID ChildID ethnicity
0 1 1 White
1 2 2 South Asian
2 3 3 Other
3 4 4 Other
4 4 5 Other
5 5 6 Other
为此,我运行了以下代码,类似于answer 中提供的代码:
col = 'ethnicity'
conditions = [ (df[col] in ('White British', 'White Other')),
(df[col] in ('Indian', 'Pakistani', 'Bangladeshi')),
(df[col] in ('Other', 'Black', 'Mixed-White and Black', 'Mixed-White and South Asian'))]
choices = ['White', 'South Asian', 'Other']
df["ethnicity"] = np.select(conditions, choices, default=np.nan)
但是在运行它时,我收到以下错误: ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
知道为什么我会收到此错误吗?我没有正确处理字符串比较吗?我正在使用类似的技术来操作我的数据集中的其他特征,并且在那里运行良好。
【问题讨论】:
-
你应该接受我的回答。