【发布时间】:2017-07-29 08:26:06
【问题描述】:
如果一列中的值介于其他列中的两个值之间,我无法将权重 (int) 添加到新的 Pandas DataFrame 列。但是,我可以使用 True/False 值(如果我使用 astype,则为 0/1 值)创建列。
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [3,6,4]})
df
a b c
0 1 4 3
1 2 5 6
2 3 6 4
这行得通:
df['between_bool'] = df['c'].between(df['a'], df['b'])
df
a b c between_bool
0 1 4 3 True # 3 is between 1 and 4
1 2 5 6 False # 6 is NOT between 2 and 5
2 3 6 4 True # 4 is between 3 and 6
但是,这不起作用:
df['between_int'] = df['c'].apply(lambda x: 2 if df['c'].between(df['a'], df['b']) else 0)
上面的代码产生如下错误:
Traceback (most recent call last):
File "C:\Python36\envs\PortfolioManager\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-14-0aa1e7cfd5c2>", line 1, in <module>
df['between_int'] = df['c'].apply(lambda x: 2 if df['c'].between(df['a'], df['b']) else 0)
File "C:\Python36\envs\PortfolioManager\lib\site-packages\pandas\core\series.py", line 2294, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1207, in pandas.lib.map_infer (pandas\lib.c:66124)
File "<ipython-input-14-0aa1e7cfd5c2>", line 1, in <lambda>
想要的输出是:
a b c between_int
0 1 4 3 2 # 3 is between 1 and 4
1 2 5 6 0 # 6 is NOT between 2 and 5
2 3 6 4 2 # 4 is between 3 and 6
有什么想法吗?
【问题讨论】: