【问题标题】:I can not slice the data for a unique date我无法对唯一日期的数据进行切片
【发布时间】:2020-03-20 11:33:51
【问题描述】:

我一直在运行一系列代码,它们似乎都运行良好,直到我进入最后一步。以下是我运行的一些代码:

rds = pd.read_csv('RDS-A.csv')
print(rds.head())
print(rds.shape)
print(rds.describe())
rds_2015 = rds.loc['2015-01-01':'2015-12-31']
print(rds_2015.loc['2015-01-30'])

错误

KeyError Traceback (最近一次调用最后一次) get_loc(self, key, method, 容差)2896 尝试:-> 2897 返回 self._engine.get_loc(key) 2898 除了 KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() KeyError: '2015-01-30'

【问题讨论】:

  • 显然没有索引为“2015-01-30”的数据,但如果您不提供输入数据等更多信息,我们将无法为您提供帮助
  • 就像我说的。如果您不给我们一些数据来查看,我们将无法帮助您
  • 我从 yahoo Finance 获得了 01-01-2008 到 31-12-2018 的 RDS-A 股票数据
  • rds_2015 = rds.loc['2015-01-01':'2015-12-31'] 返回一个空数据框。你在下一行得到一个错误。看看我的回答,可能对你有帮助

标签: python indexing slice analysis finance


【解决方案1】:

试试:

import pandas as pd
rds = pd.read_csv('RDS-A.csv')
rds['Date'] = pd.to_datetime(rds['Date'])
rds.set_index('Date', inplace=True)
rds_2015 = rds['2015']

如果要按日期对数据进行切片,则必须具有 datetime 格式。为简单起见,您可以将该列设置为索引。然后你可以轻松地做某事像rds['2015'] 来获取所有 2015 年的值

【讨论】:

  • luigigi 我爱你。我尝试了 15 个小时的东西,你解决了。非常感谢
  • 很高兴它有帮助。如果您接受答案会很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多