我有以下数据框:
S A
1 1
1 0
2 1
2 0
我想创建一个新的'Result'
根据 A 列和 S 列的值计算的列。
我写了下面的嵌套np.where
code
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
我的代码有什么问题吗?
您应该使用嵌套的 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
output:
| | S | A | Result |
|---|---|---|--------|
| 0 | 1 | 1 | 1 |
| 1 | 1 | 0 | 0 |
| 2 | 2 | 1 | 0 |
| 3 | 2 | 0 | 1 |
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)