Hat*_*sut 5 python ternary-operator pandas
我想根据现有列的值为列分配值。这段代码有效,但我想就地进行,也许使用assign或apply。
如果这可以在一个步骤中完成,它也将避免从int到的隐式转换float,下面发生。
我已经包含了我使用 的尝试assign,这会引发ValueError.
import pandas as pd
original = pd.DataFrame({'col': ['a', 'b', 'c']})
d = original.copy()
d.loc[d.col.isin(['b', 'x']), 'new'] = 1
d.loc[~d.col.isin(['b', 'x']), 'new'] = 99
d
# : col new
# : 0 a 99.0
# : 1 b 1.0
# : 2 c 99.0
# original.assign(new=lambda x: (1 if x.col.isin(['b', 'x']) else 99)) # ValueError
Run Code Online (Sandbox Code Playgroud)
您可以使用numpy.where():
import numpy as np
original["new"] = np.where(original["col"].isin(["b", "x"]), 1, 99)
print(original)
# col new
#0 a 99
#1 b 1
#2 c 99
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3472 次 |
| 最近记录: |