Python:根据其他两列(包括负值)有条件地创建新列

Python: Conditionally Create New Column Based on Two Other Columns (including negative values)

目前我有下面的数据框。前两列是我所拥有的……我想创建第三列 ('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)

您可以将 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

检查列的绝对值 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 中的一个例子。

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