【问题标题】:Dataframe.multiply method generate NaN valuesDataframe.multiply 方法生成 NaN 值
【发布时间】:2020-05-14 17:10:56
【问题描述】:

我正在尝试使用数据框的 .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 multiplication


【解决方案1】:

您必须首先将您的索引转换为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

【讨论】:

  • 'axis="rows"' 注释从何而来?文档显示 0 或“索引”
  • 对不起,我不记得它可能在旧文档中。
猜你喜欢
  • 2017-03-13
  • 1970-01-01
  • 2023-03-06
  • 2012-03-06
  • 2018-02-22
相关资源
最近更新 更多