我有一个数据框,将时间序列值存储在宽表格中:
market_value = pd.DataFrame( {'AAPL':[100,200,400], 'IBM':[50,100,200],'MSFT':[50,200,400]},
index = ['2013-12-31', '2014-12-31', '2015-12-31'] )
In [1]: market_value
Out [1]:
AAPL IBM MSFT
2013-12-31 100 50 50
2014-12-31 200 100 200
2015-12-31 400 200 400
我想计算每只股票在任何给定时间点的横截面重量。以2013年12月31日为例,AAPL的权重为:
100 / (100+50+50) = 0.50
所以结果应该是这样的:
In [2]: weight
Out [2]:
AAPL IBM MSFT
2013-12-31 0.50 0.25 0.25
2014-12-31 0.40 0.20 0.40
2015-12-31 0.40 0.20 0.40
在 Matlab 中,这是通过以下方式完成的:
weight = market_value ./ repmat( sum(market_value,2), 1, 3 )
在 Python 中执行此操作最优雅的方法是什么?
您需要除以 div
sum
按行:
print (market_value.sum(axis=1))
2013-12-31 200
2014-12-31 500
2015-12-31 1000
dtype: int64
print (market_value.div(market_value.sum(axis=1), axis=0))
AAPL IBM MSFT
2013-12-31 0.5 0.25 0.25
2014-12-31 0.4 0.20 0.40
2015-12-31 0.4 0.20 0.40
我是一名优秀的程序员,十分优秀!