【发布时间】:2020-08-06 08:54:56
【问题描述】:
我有以下Timeseries 数据。
price_per_year.head()
price
date
2013-01-02 20.08
2013-01-03 19.78
2013-01-04 19.86
2013-01-07 19.40
2013-01-08 19.66
price_per_year.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 782 entries, 2013-01-02 to 2015-12-31
Data columns (total 1 columns):
price 756 non-null float64
dtypes: float64(1)
memory usage: 12.2 KB
我正在尝试使用以下代码提取 3 年的数据。为什么我得到KeyError: '2014',当如下所示的数据清楚地包含年份'2014'时。感谢任何输入。
price_per_year['2014'].head()
price
date
2014-01-01 NaN
2014-01-02 39.59
2014-01-03 40.12
2014-01-06 39.93
2014-01-07 40.92
prices = pd.DataFrame()
for year in ['2013', '2014', '2015']:
price_per_year = price_per_year.loc[year, ['price']].reset_index(drop=True)
price_per_year.rename(columns={'price': year}, inplace=True)
prices = pd.concat([prices, price_per_year], axis=1)
KeyError: '2014'
代码行price_per_year.loc['2014', ['price']],在for loop之外独立使用时,工作正常,而price_per_year['price'][year]在for loop中使用时不起作用。
for year in ['2013', '2014', '2015']:
price_per_year = price_per_year['price'][year].reset_index(drop=True)
KeyError: 'price'
price_per_year.loc[price_per_year.index.year == 2014, ['price']] 代码行在 for loop 外部独立使用时,price_per_year.loc[price_per_year.index.year == year, ['price']] 在for loop 内部使用时都会出错。
for year in ['2013', '2014', '2015']:
price_per_year.loc[price_per_year.index.year == '2014', ['price']].reset_index(drop=True)
TypeError: Cannot convert input [False] of type <class 'bool'> to Timestamp
【问题讨论】:
标签: python-3.x pandas time-series subset