У меня есть следующий мультииндексированный фрейм данных Pandas:
toy.to_json()
'{"["ISRG","Price"]":{"2004-12-31":10.35,"2005-01-28":10.35,"2005-03-31":14.15,"2005-04-01":14.15,"2005-04-29":14.15,"2005-06-30":15.51,"2005-07-01":15.51,"2005-07-29":15.51,"2005-09-30":20.77,"2005-10-28":20.77},"["ISRG","Price_high"]":{"2004-12-31":13.34,"2005-01-28":13.34,"2005-03-31":16.27,"2005-04-01":16.27,"2005-04-29":16.27,"2005-06-30":17.35,"2005-07-01":17.35,"2005-07-29":17.35,"2005-09-30":25.96,"2005-10-28":25.96},"["ISRG","Price_low"]":{"2004-12-31":7.36,"2005-01-28":7.36,"2005-03-31":12.03,"2005-04-01":12.03,"2005-04-29":12.03,"2005-06-30":13.67,"2005-07-01":13.67,"2005-07-29":13.67,"2005-09-30":15.58,"2005-10-28":15.58},"["EW","Price"]":{"2004-12-31":9.36,"2005-01-28":9.36,"2005-03-31":10.47,"2005-04-01":10.47,"2005-04-29":10.47,"2005-06-30":11.07,"2005-07-01":11.07,"2005-07-29":11.07,"2005-09-30":10.86,"2005-10-28":10.86},"["EW","Price_high"]":{"2004-12-31":10.56,"2005-01-28":10.56,"2005-03-31":11.07,"2005-04-01":11.07,"2005-04-29":11.07,"2005-06-30":11.69,"2005-07-01":11.69,"2005-07-29":11.69,"2005-09-30":11.56,"2005-10-28":11.56},"["EW","Price_low"]":{"2004-12-31":8.15,"2005-01-28":8.15,"2005-03-31":9.87,"2005-04-01":9.87,"2005-04-29":9.87,"2005-06-30":10.46,"2005-07-01":10.46,"2005-07-29":10.46,"2005-09-30":10.16,"2005-10-28":10.16},"["volatility",""]":{"2004-12-31":null,"2005-01-28":null,"2005-03-31":null,"2005-04-01":null,"2005-04-29":null,"2005-06-30":null,"2005-07-01":null,"2005-07-29":null,"2005-09-30":null,"2005-10-28":null}}'
Я хочу с помощью одной строки кода создать новый столбец с именем 'volatility' на втором уровне (то есть под "ISGR" и "EW"), который будет определяться следующим выражением:
(100 * (Price_high - Price_low)/Price).round()
У меня две проблемы:
а) я не могу создать новый столбец
б) не могу назначить это
Вот код, который я использовал для создания столбца, но он не работает:
idx = pd.IndexSlice
100 *( toy.loc[:, idx[:, 'Price_high']] - toy.loc[:, idx[:, 'Price_low']].div(toy.loc[:, idx[:, 'Price']])).round()
Эта строка кода возвращает NaN: