【发布时间】:2021-07-29 18:10:19
【问题描述】:
我有一个名为 maximoVerano 的 DataFrame 并想重新索引它,因为我将附加具有不同年份索引的其他 DataFrame。但是,当我想使用 set-index 时,如您在示例示例中所见,我收到错误代码:
KeyError: '[2001] 均不在列中'
示例代码
>>> maximosVerano
demanda demanda31.5 ... fechaHoraMaxDem31.5 fechaHoraMaxDem63
0 28.037 4.1211 ... 2001-03-16 21:00:00 2001-01-15 22:00:00
[1 rows x 6 columns]
>>> type(maximosVerano)
<class 'pandas.core.frame.DataFrame'>
>>> maximosVerano.index
RangeIndex(start=0, stop=1, step=1)
>>> maximosVerano.set_index([anio], inplace=True)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 4727, in set_index
raise KeyError(f"None of {missing} are in the columns")
KeyError: 'None of [2001] are in the columns'
>>> anio
2001
问题
在这种简单的情况下,如何将索引设置为 DataFrame 并获取索引 2001?
请注意,索引的类型最初是一个范围。也许问题就在那里,但我不确定。
【问题讨论】:
-
仔细检查the documentation 中的
set_index():“使用现有列设置 DataFrame 索引。” (强调我的)。
标签: python python-3.x pandas dataframe