从Pandas Dataframe中删除取消行

Nie*_*tse 5 python dataframe pandas

我有一份发给客户的发票清单.但是,有时会发送不良发票,稍后会取消.我的Pandas Dataframe看起来像这样,除了更大(约300万行)

index | customer | invoice_nr | amount | date
---------------------------------------------------
0     | 1        | 1          | 10     | 01-01-2016
1     | 1        | 1          | -10    | 01-01-2016
2     | 1        | 1          | 11     | 01-01-2016
3     | 1        | 2          | 10     | 02-01-2016
4     | 2        | 3          | 7      | 01-01-2016
5     | 2        | 4          | 12     | 02-01-2016
6     | 2        | 4          | 8      | 02-01-2016
7     | 2        | 4          | -12    | 02-01-2016
8     | 2        | 4          | 4      | 02-01-2016
...   | ...      | ...        | ...    | ...
...   | ...      | ...        | ...    | ...
Run Code Online (Sandbox Code Playgroud)

现在,我想删除所有行customer,invoice_nr并且date相同,但amount具有相反的值.
发票的更正始终在同一天使用相同的发票编号进行.发票号唯一地绑定到客户和总是对应于一个事务(其可以包括多个组件,例如用于customer = 2,invoice_nr = 4).发票的更正仅发生在更改已amount收费或amount更小的组件中.因此,取消的值不会重复invoice_nr.

任何帮助如何编程这将非常感激.

piR*_*red 3

def remove_cancelled_transactions(df):
    trans_neg = df.amount < 0
    return df.loc[~(trans_neg | trans_neg.shift(-1))]

groups = [df.customer, df.invoice_nr, df.date, df.amount.abs()]
df.groupby(groups, as_index=False, group_keys=False) \
  .apply(remove_cancelled_transactions)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述