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'])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With