0

Got a dataframe with the return of some assets, df. I want to create a new one with the excess of returns, i.e., the difference between each column and 1m_Tbill.

In[2]: df
Out[2]: 
               sp500  1m_Tbill       MCD       LUV       AIG
Period                                                      
1997-01-31  0.061317    0.0045  0.002755  0.000000  0.118938
1997-02-28  0.005928    0.0039 -0.047802  0.068707 -0.001032
1997-03-31 -0.042614    0.0043  0.092486 -0.058511 -0.029132
1997-04-30  0.058406    0.0043  0.132275  0.242938  0.094782
1997-05-30  0.058577    0.0049 -0.059206 -0.063216  0.053502
1997-06-30  0.043453    0.0037 -0.038557  0.004854  0.104155
1997-07-31  0.078123    0.0043  0.112549  0.120773  0.069456
1997-08-29 -0.057446    0.0041 -0.118233 -0.034084 -0.113850

I've tried to do this with the following code

R0 = df['1m_Tbill']
Re = df[['MCD','LUV','AIG','sp500']]
Re['sp500'] -= R0

However, this is throwing me the following warning

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  Re['sp500'] -= R0

How's the proper way to do this?

foreignvol
  • 681
  • 2
  • 7
  • 15
  • But is your intention to make a copy of the dataframe? Why aren't you doing `df['sp500'] -= df['1m_Tbill']`. You could use: `df.copy()[['MCD','LUV','AIG','sp500']]` or `df.loc[:,['MCD','LUV','AIG','sp500']]`. – Anton vBR Apr 12 '18 at 17:50
  • Another thing... The error even points to the link http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy explaining why chained indexing is dangerous and what it means. – Anton vBR Apr 12 '18 at 17:54
  • While this is a set with copy warning problem, I don't think the solution they want is in that duplicate. The solution to this problem is to use `.rsub()`, so https://stackoverflow.com/questions/43770401/subtract-pandas-columns-from-a-specified-column ? `df[['1m_bill', 'sp500', 'MCD', 'LUV', 'AIG']].rsub(df['1m_bill'],0)` – ALollz Apr 12 '18 at 18:01
  • @ALollz Sure, that's an option. Added it to the dupe list. – miradulo Apr 12 '18 at 18:07

0 Answers0