我有这个:
df['new'] = df[['col1', 'col2']].pct_change(axis=1)
我想要在col1和col2中跨行更改百分比。但是我收到了错误:
ValueError: Wrong number of items passed 2, placement implies 1
我做错了什么?
答案 0 :(得分:2)
百分比更改函数返回一个包含两列的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
您想要的行之间的百分比变化存储在最后一列(在本例中为“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