【问题标题】:Python: Conditionally Create New Column Based on Two Other Columns (including negative values)Python:根据其他两列有条件地创建新列(包括负值)
【发布时间】:2017-10-13 13:22:33
【问题描述】:

目前我有下面的数据框。前两列是我所拥有的......我想创建第三列('Value_2_Replaced)。

基本上,如果 Value_1 是一个正数,那么我想将 Value_1 与 Value_2 进行比较,值较小的放在第三列。

棘手的部分是当 Value_2 为负数时。如果 Value_2 为负但大于 Value_1,我希望 Value_2_Replaced 等于 Value_1 但保留其负值。

以下是我尝试过的代码,但它不考虑负 Value_2 的情况。任何帮助是极大的赞赏!

df["Value_2_Replaced"] = df[["Value_1", "Value_2"]].min(axis=1)

【问题讨论】:

    标签: python dataframe conditional min absolute


    【解决方案1】:

    检查列的绝对值abs()

    import pandas as pd
    
    a = {"account":(1, 2), "col1":(100, 700), "col2":(200, -800)}
    
    df = pd.DataFrame.from_dict(a)
    
    def col2_replaced(df):
        if (abs(df['col1'] < abs(df['col2']))) and df['col2'] < 0:
            return -df['col1']
        elif (abs(df['col1'] < abs(df['col2']))) and df['col2'] > 0:
            return df['col1']
        else:
            return df['col2']
    
    df['col2_replaced'] = df.apply(col2_replaced, axis=1)
    

    dataframe before running function

    dataframe after running function

    这是我放在 jupyter notebook 中的一个例子。

    该函数检查有问题的两列的绝对值并进行比较。然后,当调用该函数时,它会创建一个新列,从而产生您在示例屏幕截图中寻找的输出

    【讨论】:

      【解决方案2】:

      您可以将Value_2 的符号乘以Value_1Value_2 列的绝对最小值:

      df["Value_2_Replaced"] = pd.np.sign(df.Value_2) * df[["Value_1", "Value_2"]].abs().min(1)
      
      df
      #Account  Value_1   Value_2   Value_2_Replaced
      #0     A      100       200             100
      #1     B      200       400             200
      #2     C      300      -400            -300
      #3     D      700      -800            -700
      

      【讨论】:

      • 似乎奏效了!没想到你可以叫出这样一个专栏的标志......太棒了:)非常感谢
      猜你喜欢
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2020-06-02
      • 2022-07-05
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多