Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate pct_change() in pandas across two columns, row by row?

Tags:

python

pandas

I have this:

df['new'] = df[['col1', 'col2']].pct_change(axis=1)

I want the percent change across rows in col1 and col2. However I am getting the error:

ValueError: Wrong number of items passed 2, placement implies 1

What am I doing wrong?

like image 566
Hana Avatar asked Jun 13 '18 18:06

Hana


People also ask

How do you calculate percentage difference in pandas?

Pandas DataFrame pct_change() Method The pct_change() method returns a DataFrame with the percentage difference between the values for each row and, by default, the previous row. Which row to compare with can be specified with the periods parameter.


1 Answers

The percent change function is returning a pandas DataFrame object with two columns! This is why you see the ValueError where 1 item is expected instead of two.

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

The percent change across rows that you want is stored in the last column ('col2' in this case) so just choose that last column to populate the 'new' column. In this case we compute a 200% change for every row.

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
like image 174
Charles Parr Avatar answered Oct 14 '22 18:10

Charles Parr