Dataframe.multiply方法生成NaN值。

问题描述 投票:1回答:1

我试图使用数据框架的.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

python pandas dataframe multiplying
1个回答
0
投票

你必须先将你的指数转换为 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
© www.soinside.com 2019 - 2024. All rights reserved.