如何将数组乘以数据帧的列,然后将这些列与数据框中的新列相加?
我尝试使用下面的代码,但不知何故错误的数字:
AAPL Portfolio ACN
Date
2017-01-03 116.150002 1860.880008 116.459999
2017-01-04 116.019997 1862.079960 116.739998
2017-01-05 116.610001 1852.799992 114.989998
2017-01-06 117.910004 1873.680056 116.300003
...
它的外观如下:
AAPL Portfolio ACN
Date
2017-01-03 116.150002 1046.900003 116.459999
2017-01-04 116.019997 1047.779978 116.739998
2017-01-05 116.610001 1041.389994 114.989998
2017-01-06 117.910004 1053.140031 116.300003
...
代码如下所示。可能是我认为太复杂,因此代码没有意义:
import pandas_datareader.data as pdr
import pandas as pd
import datetime
start = datetime.datetime(2017, 1, 1)
end = datetime.datetime(2017, 3, 17)
ticker_list = ["AAPL","ACN"]
position_size = [4,5]
for i in range(0,len(ticker_list)):
#print(i)
DataInitial = pdr.DataReader(ticker_list[i], 'yahoo', start, end)
ClosingPrices[ticker_list[i]] = DataInitial[['Close']]
ClosingPrices['Portfolio'] = ClosingPrices['Portfolio'] + ClosingPrices[ticker_list[i]]*position_size[i]
print(ClosingPrices)
我想要的是:
2017-01-03: 116.150002*4+116.150002*5
2017-01-03: 116.019997*4+116.739998*5
等...
答案 0 :(得分:1)
如果需要:
2017-01-03: 116.150002*4+116.150002*5
2017-01-03: 116.019997*4+116.739998*5
然后使用来自dict
的值的多列的concat
和所有列的最后sum
:
ticker_list = ["AAPL","ACN"]
position_size = [4,5]
d = dict(zip(ticker_list,position_size))
print (pd.concat([ClosingPrices[col] * d[col] for col in ticker_list], axis=1))
AAPL ACN
Date
2017-01-03 400.000000 500.000000
2017-01-04 464.079988 583.699990
2017-01-05 466.440004 574.949990
2017-01-06 471.640016 581.500015
ClosingPrices['Portfolio'] = pd.concat([ClosingPrices[col] * d[col] for col in ticker_list],
axis=1).sum(axis=1)
print (ClosingPrices)
AAPL Portfolio ACN
Date
2017-01-03 100.000000 900.000000 100.000000 <-for testing values was changed to 100
2017-01-04 116.019997 1047.779978 116.739998
2017-01-05 116.610001 1041.389994 114.989998
2017-01-06 117.910004 1053.140031 116.300003