Python 条件变换

Python conditional transform


companies_id     transaction_month     count    
    0                2020-10-01          3
    1                2020-10-01          5
    1                2020-11-01          5
    1                2020-12-01         18
    1                2021-01-01          8

I want the result to be like

companies_id      transaction_month     count       first_month
     0                2020-10-01          3           
     1                2020-10-01          5          2020-10-01 
     1                2020-11-01          5          2020-10-01 
     1                2020-12-01         18          2020-10-01 
     1                2021-01-01          8          2020-10-01 

这是我的数据集我想添加一个名为“第一个月”的新列,该列应包含来自交易月份列的值,其中相应的计数为 >=5。

例如: 如果 companies_id 1:

前 5 笔或更多笔交易发生在 2020 年 10 月 1 日,因此“第一个月”列应始终包含 2020 年 10 月 1 日,即所有 companies_id 为 1 的行。

对每组的第一个非缺失值使用 Series.where for replace transaction_month to NaN if not >=5 count and then use GroupBy.transform with GroupBy.first 到新列:

df['transaction_month'] = pd.to_datetime(df['transaction_month'])

print (df['transaction_month'].where(df['count'] >= 5))
0          NaT
1   2020-10-01
2   2020-11-01
3   2020-12-01
4   2021-01-01
Name: transaction_month, dtype: datetime64[ns]

df['first_month'] = (df['transaction_month'].where(df['count'] >= 5)
                                            .groupby(df['companies_id'])
                                            .transform('first'))

print (df)
   companies_id transaction_month  count first_month
0             0        2020-10-01      3         NaT
1             1        2020-10-01      5  2020-10-01
2             1        2020-11-01      5  2020-10-01
3             1        2020-12-01     18  2020-10-01
4             1        2021-01-01      8  2020-10-01