'Percantage change in python dataframe based on index
I have a dataframe in Python. I am looking for a way to calculate percentage change of a column based on the value of the first column of the table.
Number | Value
_____________________
1 1
1 1,5
1 1,5
1 3
2 300
2 200
2 250
2 350
... ...
This is how I would like the dataframe to look:
Number | Value | pct_change
___________________________________
1 1
1 1,5 0,5
1 1,5 0,0
1 3 1,0
2 300
2 200 -0,33
2 250 0,25
2 350 0,40
... ... ...
Solution 1:[1]
Assuming pandas, you can apply pct_change
per group:
df['pct_change'] = df.groupby('Number')['Value'].pct_change()
output:
Number Value pct_change
0 1 1.0 NaN
1 1 1.5 0.500000
2 1 1.5 0.000000
3 1 3.0 1.000000
4 2 300.0 NaN
5 2 200.0 -0.333333
6 2 250.0 0.250000
7 2 350.0 0.400000
NB. ensure that you have numeric values. The decimal separator in python is a dot .
. To convert from strings with commas, use: df['Value'] = pd.to_numeric(df['Value'].str.replace(',', '.', regex=False))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |