首页 > 解决方案 > Pandas:根据数据框的逻辑添加列

问题描述

我有一个看起来像这样的数据框

   A          B          C
0  20200608  20200507   202006
1  20200608  20200630   202006
2  20200608  20200701   202006
3  20200508  20200401   202005
4  20200508  20200507   202005
5  20200508  20200508   202005
6  20200408  20203030   202004
7  20200308  20200601   202003

我有一个函数 get_previous_month(202006) -> 202005

如果 B 中的日期 > YYYYMM -1 的 A 中的日期,我想更新我的数据框以在“D”中添加一个布尔值

A 列中的所有日期,对于 C 中相同的 YYYYMM,将是相同的

例如:在第 0 行,C 列是 202006,之前的 YYYYMM 是 202005。20200507 不大于 20200508

   A          B          C        D
0  20200608  20200507   202006   False
1  20200608  20200630   202006   True
2  20200608  20200701   202006   True
3  20200508  20200401   202005   False
4  20200508  20200507   202005   True
5  20200508  20200508   202005   True
6  20200408  20203030   202004   True
7  20200308  20200601   202003   Null

标签: pythonpandasapply

解决方案


这就是我所拥有的...

        is_current = {}

        cutoff = lambda x: pd.unique(df[df['C'] == add_months(x, -1) ]['A']).tolist()

        for i, row in df.iterrows():
            row_cutoff = cutoff(row['C'])
            if row_cutoff:
                is_current[i] = int(row['B']) > int(row_cutoff[0])
            else:
                is_current[i] = None

        is_current = [is_current.get(a) for a in range(len(is_current.keys()))]
        df['D'] = is_current
        df.reset_index(drop=True)

推荐阅读