我有以下数据帧:
S A
1 1
1 0
2 1
2 0我想创建一个新的'Result'列,它是根据列A和列S的值计算得出的。
我编写了以下嵌套的np.where代码
df['Result'] = np.where((df.S == 1 & df.A == 1), 1,
(df.S == 1 & df.A == 0), 0,
(df.S == 2 & df.A == 1), 0,
(df.S == 2 & df.A == 0), 1))))但是当我执行它时,我得到了以下错误:
SyntaxError: invalid syntax我的代码出了什么问题?
发布于 2019-01-16 21:10:50
据我所知,np.where不支持多个返回语句(至少不超过两个)。因此,要么重写np.where以产生一个True和一个False语句,并为True/False返回1/0,要么需要使用掩码。
如果重写np.where,则限制为两个结果,当条件不为真时,将始终设置第二个结果。因此它也将被设置为像(S == 5) & (A = np.nan)这样的值。
df['Result'] = np.where(((df.S == 1) & (df.A == 1)) | ((df.S == 2) & (df.A == 0)), 1, 0)使用掩码时,可以应用任意数量的条件和结果。对于您的示例,解决方案如下所示:
mask_0 = ((df.S == 1) & (df.A == 0)) | ((df.S == 2) & (df.A == 1))
mask_1 = ((df.S == 1) & (df.A == 1)) | ((df.S == 2) & (df.A == 0))
df.loc[mask_0, 'Result'] = 0
df.loc[mask_1, 'Result'] = 1在不满足任何条件的情况下,结果将设置为np.nan。这是imho故障保护,因此应该使用。但是,如果您想在这些位置使用零,只需将Results列初始化为零即可。
当然,这可以在特殊情况下简化,比如只有1和0作为结果,并通过使用dicts或其他容器扩展到任意数量的结果。
发布于 2019-10-27 07:06:54
您应该使用嵌套的np.where。它就像sql case子句。但是当数据中有nan时要小心。
df=pd.DataFrame({'S':[1,1,2,2],'A':[1,0,1,0]})
df['Result'] = np.where((df.S == 1) & (df.A == 1), 1, #when... then
np.where((df.S == 1) & (df.A == 0), 0, #when... then
np.where((df.S == 2) & (df.A == 1), 0, #when... then
1))) #else
df输出:
| | S | A | Result |
|---|---|---|--------|
| 0 | 1 | 1 | 1 |
| 1 | 1 | 0 | 0 |
| 2 | 2 | 1 | 0 |
| 3 | 2 | 0 | 1 |发布于 2020-10-31 23:36:57
如果你有非常嵌套的操作,我推荐使用numpy.select。
df = pd.DataFrame({
"S": [1, 1, 2, 2],
"A": [1, 0, 1, 0]
})
# you could of course combine the clause (1, 4) and (2, 3) with the '|' or operator
df['RESULT'] = np.select([
(df.S == 1) & (df.A == 1),
(df.S == 1) & (df.A == 0),
(df.S == 2) & (df.A == 1),
(df.S == 2) & (df.A == 0)
], [1, 0, 0, 1])https://stackoverflow.com/questions/54217397
复制相似问题