How To Calculate Percent Change Compared To The Beginning Value Using Pandas?
I have a DataFrame and need to calculate percent change compared to the beginning of the year by companies. Is there any way to use pct_change() or other method to perform this tas
Solution 1:
Sounds like you are looking for an expanding_window
version of pct_change()
. This doesn't exist out of the box AFAIK, but you could roll your own:
df.groupby('security')['price'].apply(lambda x: x.div(x.iloc[0]).subtract(1).mul(100))
Solution 2:
This works, assuming you're already ordered by date within each possible grouping.
def pct_change(df):
df['pct'] = 100 * (1 - df.iloc[0].price / df.price)
returndf
df.groupby('security').apply(pct_change)
Solution 3:
I had the same problem, but solved it his way:
(only difference was that the columns would be your company and not the row.)
for each column of my dataframe I did:
df[column] = df[column].pct_change().cumsum()
pct_change()
calculates the change between now and the last value, and cumcum()
adds it all together.
Post a Comment for "How To Calculate Percent Change Compared To The Beginning Value Using Pandas?"