[英]Is there a better why than this nested loop?
我的問題來自兩個數據幀:DF1 有許多證券需要我們定價文件 DF2 中的價格。
DF1
安全號碼密鑰 | 當前日期價格 |
---|---|
一種 | NaN |
乙 | NaN |
C | NaN |
DF2
安全 ID | 價錢 |
---|---|
一種 | 100 |
乙 | 200 |
D | 400 |
我當前有效的代碼如下所示:
for k, v in DF1['Security Number Key'].items():
for i, n in DF2['Security_ID'].items():
if v == n:
DF1['Current Date Price'][k] = DF2['Price'][i]
這有效但效率不高,因為我的數據幀比示例大得多。
我也試過使用 df.query() 但是當我得到匹配時,它返回的不僅僅是價格。
for k, v in DF1['Security Number Key'].items():
if v in DF2['Security_ID'].values:
print(DF2.query('Security_ID == @v')['Price'])
結果是輸出:
0 100
Name: Price, dtype: float64
Pandas 實際上有很多功能可以避免循環。 其中之一是合並。 您可以使用以下代碼生成的數據框,例如:
import pandas as pd
import numpy as np
DF1 = pd.DataFrame({'Security Number Key':['A','B','C'],
'Current Date Price':[np.nan,np.nan,np.nan]})
DF2 = pd.DataFrame({'Security_ID':['A','B','C'],
'Price':[100,200,300]})
DF3 = DF1.merge(DF2, left_on='Security Number Key', right_on='Security_ID', how='left')
print(DF3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.