如何有效地获得Pandas DataFrame中行之间的日志变化率?

时间:2016-07-18 19:40:29

标签: python numpy pandas dataframe series

我们说我有一些DataFrame(在我的情况下,大约有10000行,这只是一个最小的例子

>>> import pandas as pd

>>> sample_df = pd.DataFrame(
        {'col1': list(range(1, 10)), 'col2': list(range(10, 19))})

>>> sample_df

   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14
5     6    15
6     7    16
7     8    17
8     9    18

出于我的目的,我需要为我的DataFrame中的每个ln(col_i(n+1) / col_i(n))计算由col_i表示的系列,其中n表示行号。 如何计算

背景知识

我知道我可以使用

以非常简单的方式获取每列之间的差异
>>> sample_df.diff()

   col1  col2
0   NaN   NaN
1     1     1
2     1     1
3     1     1
4     1     1
5     1     1
6     1     1
7     1     1
8     1     1

或使用

更改百分比,即(col_i(n+1) - col_i(n))/col_i(n+1)
>>> sample_df.pct_change()

       col1      col2
0       NaN       NaN
1  1.000000  0.100000
2  0.500000  0.090909
3  0.333333  0.083333
4  0.250000  0.076923
5  0.200000  0.071429
6  0.166667  0.066667
7  0.142857  0.062500
8  0.125000  0.058824

我一直在努力用一种简单的方法来获得前一个连续列的直接划分。如果我知道如何做到这一点,我可以在事后将自然对数应用于系列中的每个元素。

目前为了解决我的问题,我正在尝试创建另一列,每列的行元素向下移动1,然后在两列之间应用公式。不过,这对我来说似乎很麻烦且次优。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:4)

只需使用np.log:

np.log(df.col1 / df.col1.shift())

你也可以按照@nikita的建议使用申请,但速度会慢一些。

此外,如果您想对整个数据框执行此操作,您可以这样做:

np.log(df / df.shift())

答案 1 :(得分:3)

IIUC:

比率的对数是日志的差异:

sample_df.apply(np.log).diff()

或者更好的是:

np.log(sample_df).diff()

enter image description here

时序

enter image description here

答案 2 :(得分:1)

您可以使用shift,这可以完成您的建议。

>>> sample_df['col1'].shift()
0    NaN
1    1.0
2    2.0
3    3.0
4    4.0
5    5.0
6    6.0
7    7.0
8    8.0
Name: col1, dtype: float64

最终的答案是:

import math
(sample_df['col1'] / sample_df['col1'].shift()).apply(lambda row: math.log(row))

0         NaN
1    0.693147
2    0.405465
3    0.287682
4    0.223144
5    0.182322
6    0.154151
7    0.133531
8    0.117783
Name: col1, dtype: float64