我有兩個pandas資料框架,像這樣。
df = pd.DataFrame([
['ABC0876', 20200103] 。
['DEG9871', 20210201] 。
['USQ5321', 20201101] 。
['RCF2345', 20211004], columns = ['RCF2345', >20211004]
], columns = ['Key', 'PricingDate'])
master = pd.DataFrame([
['ABC0876', 'ZS01', 20190101, 20200130] 。
['ABC0876', 'ZS02', 20200101, 20200213] 。
['DEG9871', 'ZSD1', 20210201, 20220121] 。
['USQ5321', 'ZS01', 20201001, 20220908] 。
['RCF2345', 'ZS02', 20201004, 20211013]
], columns = ['Key'/span>, 'Condition'/span>, 'Valid_From'/span>, 'Valid_To'/span>] )
目的是為每個鍵獲得唯一的有效條件。我嘗試了以下方法
def Numconditions(Key, PricingDate)。
unqconds = master.loc[(master['Key']==Key) & (master['Valid_To']>=PricingDate),'Condition'].unique()
return unqconds
df['Unqconds'] = df.apply(lambda row: Numconditions(row['Key'], row['PricingDate']), axis=1)
資料幀非常大,而且運行時間很長。有誰能建議快速解決這個問題,以減少運行時間?
uj5u.com熱心網友回復:
你可以在檢查條件之前合并你的2個資料框架,并將行減少到一個唯一值的串列中:
out = pd.merge(df, master, on='Key', how='left')
.query('Valid_To >= PricingDate')
.groupby('Key', sort=False)['Condition'].unique()
.重命名('Unqconds')
df = df.set_index('Key').join(out).reset_index()
輸出:
>>> df
關鍵的PricingDate Unqconds
0 ABC0876 20200103 [ZS01, ZS02] 。
1 DEG9871 20210201 [ZSD1]
2 USQ5321 20201101 [ZS01]
3 RCF2345 20211004 [ZS02]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/326391.html
標籤:
