Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas : add column to multiindex dataframe at the end

Tags:

python

pandas

Can someone please help me add a column to a multiindex dataframe?

I have the following multiindex dataframe:

                    price     
sym     i_date
MSFT    2017-04-04  100.78    
        2017-04-05  100.03    
        2017-04-06  100.76    
        2017-04-07  100.76    

AAPL    2017-04-04  144.77      
        2017-04-05  144.02
        2017-04-06  143.66
        2017-04-07  143.66

I want to add a column after the price column which is the natural log of the prices:

                    price      ln price
sym     i_date
MSFT    2017-04-04  100.78       <ln (100.78)>
        2017-04-05  100.03       <ln (100.03)>
        2017-04-06  100.76       <ln (100.76)>
        2017-04-07  100.76       <ln (100.76)>

AAPL    2017-04-04  144.77       <ln (144.77)>
        2017-04-05  144.02       <ln (144.02)>
        2017-04-06  143.66       <ln (143.66)>
        2017-04-07  143.66       <ln (143.66)>

I tried the following but it doesn't change the dataframe.

for stk_sym in df.index.get_level_values('stk_sym').unique():
    df.loc[stk_sym]['ln price'] = np.log(df.ix[stk_sym]['price'])
like image 931
Slayer Avatar asked Jan 31 '26 12:01

Slayer


1 Answers

You can set the value as:

Code:

df['ln price'] = np.log(df['price'])

Test Code:

df = pd.read_fwf(StringIO(u"""
    sym     i_date      price
    MSFT    2017-04-04  100.78    
    MSFT    2017-04-05  100.03    
    MSFT    2017-04-06  100.76    
    MSFT    2017-04-07  100.76    
    AAPL    2017-04-04  144.77      
    AAPL    2017-04-05  144.02
    AAPL    2017-04-06  143.66
    AAPL    2017-04-07  143.66"""),
                 header=1).set_index(['sym', 'i_date'])

df['ln price'] = np.log(df['price'])

print(df)

Results:

                  price  ln price
sym  i_date                      
MSFT 2017-04-04  100.78  4.612940
     2017-04-05  100.03  4.605470
     2017-04-06  100.76  4.612741
     2017-04-07  100.76  4.612741
AAPL 2017-04-04  144.77  4.975146
     2017-04-05  144.02  4.969952
     2017-04-06  143.66  4.967449
     2017-04-07  143.66  4.967449
like image 115
Stephen Rauch Avatar answered Feb 02 '26 01:02

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!