【问题标题】:Create Pandas DataFrame column with weight if value in 1 column is between values in 2 other columns如果 1 列中的值介于其他 2 列中的值之间,则创建具有权重的 Pandas DataFrame 列
【发布时间】: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

有什么想法吗?

【问题讨论】:

    标签: python pandas lambda


    【解决方案1】:

    希望我理解正确,但如果您只是想在这种情况下添加固定权重 2,则一种选择是执行以下操作:

    import numpy as np
    df['between_int'] = np.where(df['c'].between(df['a'], df['b']), 2, 0)
    

    如果您不想导入 numpy,也可以执行以下操作:

    df['between_int'] = 0
    df.loc[df['c'].between(df['a'], df['b']), 'between_int'] = 2
    

    希望这会有所帮助!

    【讨论】:

    • 这正是我想要的。谢谢。
    【解决方案2】:

    我认为你最初想用apply 做的是:

    df['between_int'] = df.apply(lambda x: 2 if x['c'] in range(x['a'], x['b']) else 0, axis=1)
    

    看看与你的不同:

    1. apply 在数据框上 df 不是意甲 df['c']
    2. 通过x['c'] 而不是df['c'] 获取您要检查的值,因为您的 lambda 是 x 的函数
    3. 因为我将df['c'] 更改为x['c'] 我不能再使用betweenin range
    4. 对于这两个边界,通过x['a']x['b'] 调用它们,原因与第 2 点相同
    5. 最后,不要忘记 axis=1,因为现在 apply 在数据框上

    无论如何,swebbo 的解决方案完美运行!

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多