My DataFrame is:
import pandas as pd
df = pd.DataFrame(
{
'a': [20, 30, 2, 5, 10]
}
)
Expected output is pct_change()
of a
:
a pct_change
0 20 -50.000000
1 30 50.000000
2 2 -93.333333
3 5 150.000000
4 10 100.000000
I want to compare df.a.iloc[0]
with 40 for the first value of pct_change
. If I use df['pct_change'] = df.a.pct_change().mul(100)
, the first value is NaN
.
My Attempt:
def percent(a, b):
result = ((a - b) / b) * 100
return result.round(2)
df.loc[df.index[0], 'pct_change'] = percent(df.a.iloc[0], 40)
I there a better/more efficient way?