如何逐行计算两列熊猫中的 pct_change() ?

Han*_*ana 5 python pandas

我有这个:

df['new'] = df[['col1', 'col2']].pct_change(axis=1)
Run Code Online (Sandbox Code Playgroud)

我想要 col1 和 col2 中各行的百分比变化。但是我收到错误:

ValueError: Wrong number of items passed 2, placement implies 1
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Cha*_*arr 6

百分比变化函数返回一个包含两列的 Pandas DataFrame 对象!这就是为什么您会看到 ValueError,其中需要 1 项而不是 2 项。

import numpy as np
x = np.range(1,11)
y = x*3
df = pd.DataFrame()
df['col1'] = x
df['col2'] = y
df
   col1  col2
0     1     3
1     2     6
2     3     9
3     4    12
4     5    15
5     6    18
6     7    21
7     8    24
8     9    27
9    10    30

df.pct_change(axis=1)
   col1  col2
0   NaN   2.0
1   NaN   2.0
2   NaN   2.0
3   NaN   2.0
4   NaN   2.0
5   NaN   2.0
6   NaN   2.0
7   NaN   2.0
8   NaN   2.0
9   NaN   2.0
Run Code Online (Sandbox Code Playgroud)

您想要的跨行的百分比变化存储在最后一列(在本例中为“col2”),因此只需选择最后一列来填充“新”列。在这种情况下,我们为每一行计算 200% 的变化。

df['new'] = df.pct_change(axis=1)['col2']
    col1  col2  new
0     1     3  2.0
1     2     6  2.0
2     3     9  2.0
3     4    12  2.0
4     5    15  2.0
5     6    18  2.0
6     7    21  2.0
7     8    24  2.0
8     9    27  2.0
9    10    30  2.0
Run Code Online (Sandbox Code Playgroud)