在 pandas 上使用 inflation 方法时缩短 运行 时间

Improve running time when using inflation method on pandas

我正在尝试为 pandas 中的数据获取实际价格。现在,我只是在玩一年的数据(3962050 行),我花了 443 秒使用下面的代码来膨胀这些值。有没有更快的方法来找到真正的价值?是否可以使用池化?我还有很多年,如果每次都等太久。

Portion of df:
    year    quarter fare
0   1994    1      213.98
1   1994    1      214.00   
2   1994    1      214.00
3   1994    1      214.50 
4   1994    1      214.50   
import cpi
import pandas as pd

def inflate_column(data, column):
    """
    Adjust for inflation the series of values in column of the   
    dataframe data. Using cpi library.
    """
    print('Beginning to inflate ' + column)
    start_time = time.time()
    
    df = data.apply(lambda x: cpi.inflate(x[column], 
                      x.year), axis=1)
    
    print("Inflating process took", time.time() - start_time, " seconds to run")  
    return df

df['real_fare'] = inflate_column(df, 'fare')

每年你有多个值:你可以每年调用一个值,将其存储在字典中,然后使用该值而不是每次都调用 cpi.inflate

all_years = df["year"].unique()
dict_years = {}
for year in all_years:
    dict_years[year] = cpi.inflate(1.0, year)

df['real_fare'] = # apply here: dict_years[row['year']]*row['fare'] 

您可以使用 apply 填充最后一行,或者尝试使用其他方式,例如 df['real_fare']=df['fare']*...