我正在尝试使用数据帧的 .multiply 方法将数据帧逐个元素乘以一个系列。在这种情况下,将开盘价和收盘价转换为英镑。不知何故,它不断返回 NaN 值。知道问题出在哪里吗?我已经检查了两个对象中的数据类型并验证它们是浮点数。
# Subset 'Open' & 'Close' columns from sp500: dollars
dollars = sp500[['Open', 'Close']]
# Convert dollars to pounds: pounds
pounds = dollars[['Open', 'Close']].multiply(exchange['GBP/USD'], axis='rows')
# Print the head of dollars
print(dollars.head())
# Print the head of exchange
print(exchange.head())
# Print the head of pounds
print(pounds.head())
下面是输出。
Open Close
Date
2015-01-02 2058.899902 2058.199951
2015-01-05 2054.439941 2020.579956
2015-01-06 2022.150024 2002.609985
2015-01-07 2005.550049 2025.900024
2015-01-08 2030.609985 2062.139893
GBP/USD
Date
2015/01/02 0.65101
2015/01/05 0.65644
2015/01/06 0.65896
2015/01/07 0.66344
2015/01/08 0.66151
Open Close
Date
2015-01-02 NaN NaN
2015-01-05 NaN NaN
2015-01-06 NaN NaN
2015-01-07 NaN NaN
2015-01-08 NaN NaN
您必须先将索引转换为datetime
类型使用pandas.to_datetime
exchange.index = pd.to_datetime(exchange.index)
dollars.index = pd.to_datetime(dollars.index)
pounds = dollars[['Open', 'Close']].multiply(exchange['GBP/USD'], axis='rows')
pounds
Open Close
Date
2015-01-02 1340.364425 1339.908750
2015-01-05 1348.616555 1326.389506
2015-01-06 1332.515980 1319.639876
2015-01-07 1330.562125 1344.063112
2015-01-08 1343.268811 1364.126161