【发布时间】:2021-06-10 14:42:26
【问题描述】:
def __link_price(row: pd.Series) -> Union[None, float]:
if (row['fund'] == 'A') and (row['share_class'] == 'X'):
return df_hist.loc[row['date'], 'AA']
elif (row['fund'] == 'A') and (row['share_class'] == 'Y'):
return df_hist.loc[row['date'], 'AB']
elif (row['fund'] == 'B') and (row['share_class'] == 'X'):
return df_hist.loc[row['date'], 'BA']
elif (row['fund'] == 'B') and (row['share_class'] == 'Y'):
return df_hist.loc[row['date'], 'BB']
elif (row['fund'] == 'C') and (row['share_class'] == 'X'):
return df_hist.loc[row['date'], 'CA']
elif (row['fund'] == 'C') and (row['share_class'] == 'Y'):
return df_hist.loc[row['date'], 'CB']
else:
return 0
df.loc[:, 'price'] = df.apply(__link_price_at_purchase, axis=1).values
df 有 10,000+ 行,所以这段代码需要很长时间。除了每一行,我都在调用df_hist.loc 来获取值。
我正在尝试加快这部分代码的速度,然后我目前发现的选项正在使用:
df.loc[:, 'price'] = df.apply(__link_price_at_purchase, axis=1, raw=True).values
但这迫使我对row 使用基于索引的选择而不是值选择:
if (row[0] == 'A') and (row[1] == 'X')
这会降低代码的可读性。
我正在寻找一种既能加快代码速度又能提高代码可读性的方法。
【问题讨论】:
-
我会将调用链接到
np.where -
如果你有多个
if/else条件,则使用np.select,否则使用np.where。 -
也就是说,这些数据帧的格式是什么?也许你可以改用
merge_asof -
问题是第二个数据框列和行选择取决于第一个数据框行的值,因此无法合并。
-
索引和
df['date']一样吗?
标签: python pandas dataframe performance optimization