Skip to main content
 首页 » 编程设计

python之如果满足条件,则在数据框中填充一列

2025年05月04日14zengkefu

我有以下数据框:

PersonID  AmountPaid  PaymentReceivedDate  StartDate withinNYears   
1         100         2017                   2016    
2         20          2014                   2014 
1         30          2017                   2016 
1         40          2016                   2016 
4         300         2015                   2000 
5         150         2005                   2002   

我要查找的是,如果付款是在开始日期后的 n 年内进行的,则支付金额应显示在 withNYears 列中,否则您会得到 NaN。 N 年可以是任何数字,但在这个例子中假设为 2(因为我将使用它来查看结果)。

所以如果金额在 2 年内支付,基本上上面的数据框会像这样出现:

PersonID  AmountPaid  PaymentReceivedDate  StartDate  withinNYears   
1         100         2017                   2016     100 
2         20          2014                   2014     20 
1         30          2017                   2016     30  
1         40          2016                   2016     40 
4         300         2015                   2000     NaN 
5         150         2005                   2002     NaN 

有人知道怎么实现吗?干杯。

请您参考如下方法:

减去列并按 bool 掩码的标量进行比较,然后按 numpy.where 设置值, Series.where或 DataFrame.loc :

m = (df['PaymentReceivedDate'] - df['StartDate']) < 2 
df['withinNYears'] = np.where(m, df['AmountPaid'], np.nan) 
#alternatives 
#df['withinNYears'] = df['AmountPaid'].where(m) 
#df.loc[m, 'withinNYears'] = df['AmountPaid'] 
 
print (df) 
   PersonID  AmountPaid  PaymentReceivedDate  StartDate   \ 
0         1         100                 2017                    2016    
1         2          20                 2014                    2014    
2         1          30                 2017                    2016    
3         1          40                 2016                    2016    
4         4         300                 2015                    2000    
5         5         150                 2005                    2002    
 
   withinNYears   
0         100.0   
1          20.0   
2          30.0   
3          40.0   
4           NaN   
5           NaN 

编辑:

如果 StartDate 列有日期时间:

m = (df['PaymentReceivedDate'] - df['StartDate'].dt. year) < 2