gpt4 book ai didi

python - 时间序列数据框中的横截面权重

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:00 24 4
gpt4 key购买 nike

我有一个数据框,将时间序列值存储在宽表格中:

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

关于python - 时间序列数据框中的横截面权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com