【发布时间】:2017-08-10 09:37:16
【问题描述】:
我有一个数据框:
customer_id [1,2,3,4,5,6,7,8,9,10]
feature1 [0,0,1,1,0,0,1,1,0,0]
feature2 [1,0,1,0,1,0,1,0,1,0]
feature3 [0,0,1,0,0,0,1,0,0,0]
使用这个我想创建一个新变量(比如 new_var)来表示当特征 1 为 1 时 new_var=1,如果 feature_2=1 则 new_var=2,feature3=1 则 new_var=3 否则为 4。我是尝试 np.where 但虽然它没有给我错误,但它没有做正确的事情 - 所以我猜嵌套的 np.where 只适用于单个变量。在这种情况下,在 pandas 中执行嵌套 if/case 的最佳方式是什么?
我的 np.where 代码是这样的:
df[new_var]=np.where(df['feature1']==1,'1', np.where(df['feature2']==1,'2', np.where(df[feature3']==1,'3','4')))
【问题讨论】:
-
只是为了回答我自己的问题:我提到的我尝试过的 np.where 解决方案也有效 - 它没有给我正确结果的原因是因为 feature1 的数据类型是字符串而不是整数.. 所以对于任何寻找类似问题的人来说,'nested np.where' 解决方案和 'numpy.select' 解决方案 jezrael 提到的作品
标签: python pandas if-statement case-when np