2

我听说过很多关于 pandas 的应用很慢,应该尽可能少地使用。

我这里有一个情况:

df = pd.DataFrame({'Date': ['2019-01-02', '2019-01-03', '2019-01-04'],
          'Fund_ID': [9072, 9072, 9072],
          'Fund_Series': ['A', 'A', 'A'],
          'Value': [1020.0, 1040.4, 1009.188],
          'Dividend': [0.0, 0.0, 52.02]})

我想在分组后做一些调整后的加权操作,如下所示:

df['Pct_Change_Adjusted'] = df.groupby(['Fund_ID', 'Fund_Series'], as_index=False) \
                              .apply(lambda x: (x.Value + x.Dividend)/(x.Value.shift()+x.Dividend.shift())  ) \
                              .reset_index(drop=True).values[0]

print(df)

         Date  Dividend  Fund_ID Fund_Series     Value  Pct_Change_Adjusted
0  2019-01-02      0.00     9072           A  1020.000                  NaN
1  2019-01-03      0.00     9072           A  1040.400                 0.02
2  2019-01-04     52.02     9072           A  1009.188                 0.02

这里有没有其他选择apply可以提高效率或至少是第二种做事方式!!

注意:我不是在谈论 dask 和其他并行化,只是纯粹的 pandas。

必需:在不使用 apply的情况下
计算列。Pct_Change_Adjusted

4

1 回答 1

5

是的,这是 100% 可矢量化的,使用groupby.pct_change

(df.Value + df.Dividend).groupby([df.Fund_ID, df.Fund_Series]).pct_change()

0     NaN
1    0.02
2    0.02
dtype: float64

df['Pct_Change_Adjusted'] = (df.assign(Foo=df['Value'] + df['Dividend'])
                               .groupby(['Fund_ID', 'Fund_Series'])
                               .Foo
                               .pct_change())

df

         Date  Fund_ID Fund_Series     Value  Dividend  Pct_Change_Adjusted
0  2019-01-02     9072           A  1020.000      0.00                  NaN
1  2019-01-03     9072           A  1040.400      0.00                 0.02
2  2019-01-04     9072           A  1009.188     52.02                 0.02
于 2019-04-02T22:41:17.217 回答