![](/img/trans.png)
[英]How to add the missing rows from one dataframe to another based on condition in Pandas?
[英]How to add rows based on a condition with another dataframe
我有兩個數據框如下:
協議
agreement_id activation term_months total_fee
0 A 2020-12-01 24 4800
1 B 2021-01-02 6 300
2 C 2021-01-21 6 600
3 D 2021-03-04 6 300
付款
cust_id agreement_id date payment
0 1 A 2020-12-01 200
1 1 A 2021-02-02 200
2 1 A 2021-02-03 100
3 1 A 2021-05-01 200
4 1 B 2021-01-02 50
5 1 B 2021-01-09 20
6 1 B 2021-03-01 80
7 1 B 2021-04-23 90
8 2 C 2021-01-21 600
9 3 D 2021-03-04 150
10 3 D 2021-05-03 150
當付款 dataframe 中的協議 ID 的總付款等於協議 ID 中的總費用時,我想在付款 dataframe 中添加另一行。 該行將在付款下包含零值,並且日期將計算為 min(date)(來自付款)加上 term_months(來自協議)。
這是我想要的付款 dataframe 的結果:
付款
cust_id agreement_id date payment
0 1 A 2020-12-01 200
1 1 A 2021-02-02 200
2 1 A 2021-02-03 100
3 1 A 2021-05-01 200
4 1 B 2021-01-02 50
5 1 B 2021-01-09 20
6 1 B 2021-03-01 80
7 1 B 2021-04-23 90
8 2 C 2021-01-21 600
9 3 D 2021-03-04 150
10 3 D 2021-05-03 150
11 2 C 2021-07-21 0
12 3 D 2021-09-04 0
額外的行是第 11 行和第 12 行。agreement_id 'C' 和 'D' 等於協議 dataframe 中顯示的 total_fee。
import pandas as pd
import numpy as np
首先使用to_datetime()
方法將付款 dataframe 的“日期”列轉換為 datetime dtype:
payments['date']=pd.to_datetime(payments['date'])
您可以使用groupby()
方法來做到這一點:
newdf=payments.groupby('agreement_id').agg({'payment':'sum','date':'min','cust_id':'first'}).reset_index()
現在通過 boolean 掩碼獲取滿足您條件的數據:
newdf=newdf[agreement['total_fee']==newdf['payment']].assign(payment=np.nan)
注意:在上面的代碼中,我們使用了assign()
方法並將支付行設置為NaN
現在使用pd.tseries.offsets.Dateoffsets()
方法和apply()
方法:
newdf['date']=newdf['date']+agreement['term_months'].apply(lambda x:pd.tseries.offsets.DateOffset(months=x))
注意:上面的代碼給你一個警告,所以忽略那個警告,因為它是警告而不是錯誤
最后使用concat()
方法和fillna()
方法:
result=pd.concat((payments,newdf),ignore_index=True).fillna(0)
現在,如果您打印result
,您將獲得所需的 output
#output
cust_id agreement_id date payment
0 1 A 2020-12-01 200.0
1 1 A 2021-02-02 200.0
2 1 A 2021-02-03 100.0
3 1 A 2021-05-01 200.0
4 1 B 2021-01-02 50.0
5 1 B 2021-01-09 20.0
6 1 B 2021-03-01 80.0
7 1 B 2021-04-23 90.0
8 2 C 2021-01-21 600.0
9 3 D 2021-03-04 150.0
10 3 D 2021-05-03 150.0
11 2 C 2021-07-21 0.0
12 3 D 2021-09-04 0.0
注意:如果您想要完全相同的 output 然后使用astype()
方法並將支付列 dtype 從float
更改為int
result['payment']=result['payment'].astype(int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.