SoFunction
Updated on 2024-11-20

Python pandas Calculate growth rate per row and cumulative growth rate

Read data:

FacebookDf=pd.read_excel(r'D:\jupyter\Untitled Folder\Facebook 2017 Stock Data.xlsx',index_col='Date')
()

Calculate the percentage growth of the current row over the previous row (growth rate per row)

# .pct_change() returns the percentage change, the first line is filled with 0 because there is no comparable and returns Nan
# apply(lambda x: format(x, '.2%')) converts a decimal point to a percent
FacebookDf['pct_change']=FacebookDf['Close'].pct_change(1).fillna(0).apply(lambda x: format(x, '.2%'))
FacebookDf['pct_change'].head()

Calculate the percentage growth of the current row over the first row (cumulative percentage)

Close1=['2017-01-03','Close']
# apply(lambda x: (x-Close1)/Close1) Calculate cumulative growth rate
# apply(lambda x: format(x, '.2%') converts decimal points to percentages
FacebookDf['sum_pct_change']=FacebookDf['Close'].apply(lambda x: (x-Close1)/Close1).apply(lambda x: format(x, '.2%'))
FacebookDf['sum_pct_change'].head()

to this article on Python pandas calculate the growth rate of each line with the cumulative growth rate of the article is introduced to this, more related pandas calculate the growth rate of content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!