Pandas change rate Data frame after grouping

I am new to python pandas and trying to get the rate of return with pct_change (). I would like to get the monthly rate of change in the feed code. This is my current code:

In [134]:
df3 = pd.read_csv(r'C:\Users\sector_set.csv')
df3.set_index('Date', inplace= True)
df3= pd.DataFrame(df3,columns = ['Feed','Close']) # filter specific col​
grouped = df3.groupby('Feed')  #group by Feedcode
df3 = grouped.resample('BM', how=lambda x:x[-1]) #ending of every month only
df3['Rate_Return'] = df3.pct_change()  # Rate of Return of each feedcode
df3

OUTPUT:
                   Close  Rate_Return
Feed   Date
   A   2015-09-30  5.60     NaN 
       2015-10-30  5.75    0.026786  
  AAV  2015-09-30  4.32   -0.248696
       2015-10-30  4.62    0.069444

I have two problems:

  • The calculated rate of return is incorrect because it refers to the price of the previous day to calculate the return for the next feed code. For example, Feed AAV 2015-09-30 should be NaN, not -0.248696

  • I would like to delete all NaN

I am trying to calculate the return values ​​in order to get something like this:

Output:
                   Close  Rate_Return
Feed   Date
   A   2015-10-30  5.75    0.026786  
  AAV  2015-10-30  4.32    0.069444

What is the best way to do this? Thanks in advance for any help

+4
source share
1 answer

IIUC groupby Feed multiindex pct_change. df3, Rate_Return notnull

df3['Rate_Return'] = df3.groupby(level=0).pct_change() 
print df3
                 Close  Rate_Return
Feed Date                          
A    2015-09-30   5.60          NaN
     2015-10-30   5.75     0.026786
AAV  2015-09-30   4.32          NaN
     2015-10-30   4.62     0.069444

print df3[df3.Rate_Return.notnull()]
                 Close  Rate_Return
Feed Date                          
A    2015-10-30   5.75     0.026786
AAV  2015-10-30   4.62     0.069444
+2

Source: https://habr.com/ru/post/1621873/


All Articles