使用Python计算时如何添加条件?

How to add conditions when calculating using Python?

我有一个包含两个数字列的数据框。我想添加第三列来计算差异。但条件是如果第一列中的值是空白或 Nan,则差值应该是第二列中的值...

谁能帮我解决这个问题?

如有任何建议和线索,我们将不胜感激! 谢谢。

使用了示例数据框,但应该不难理解:

df = pd.DataFrame({'A': [1, 2, np.nan, 3], 'B': [10, 20, 30, 40]})

def diff(row):
    return row['B'] if (pd.isnull(row['A'])) else (row['B'] - row['A'])

df['C'] = df.apply(diff, axis=1)

原始数据框:

    A   B   
0   1.0 10  
1   2.0 20  
2   NaN 30  
3   3.0 40

apply 之后:

    A   B   C
0   1.0 10  9.0
1   2.0 20  18.0
2   NaN 30  30.0
3   3.0 40  37.0

试试这个:

def diff(row):
    if not row['col1']:
        return row['col2']
    else:
        return row['col1'] - row['col2']

df['col3']= df.apply(diff, axis=1)

这实际上不是有条件的情况,它只是一个数学运算。假设你有 df:

考虑使用 .sub() 方法的 df:

df['Diff'] = df['August Sales'].sub(df['July Sales'], fill_value=0)

returns 输出:

   July Sales  August Sales   Diff
0       459.0           477   18.0
1       422.0           125 -297.0
2       348.0           483  135.0
3       397.0           271 -126.0
4         NaN           563  563.0
5       191.0           325  134.0
6       435.0           463   28.0
7         NaN           479  479.0
8       475.0           473   -2.0
9       284.0           496  212.0

您应该尽可能使用向量化运算。这里可以使用numpy.where:

df['Difference'] = np.where(df['July Sales'].isnull(), df['August Sales'],
                            df['August Sales'] - df['July Sales'])

但是,请考虑这与将 df['July Sales'] 中的 NaN 值视为等于零完全相同。所以你可以使用 pd.Series.fillna:

df['Difference'] = df['August Sales'] - df['July Sales'].fillna(0)