我有一个名为maximoVerano
的DataFrame
,并希望重新索引它,因为我将附加其他具有不同年份索引的dataframe。然而,当我想使用set-index
时,你可以在示例示例中看到,我得到错误代码:
KeyError: 'None of [2001] are in the columns'
>>> 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:Python39libsite-packagespandascoreframe.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
>>> 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:Python39libsite-packagespandascoreframe.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 ?请注意,索引的类型最初是一个范围。也许问题是存在的,但我不确定。
试试maximosVerano.index=[anio]
set_index()
是设置一个列作为数据框的新索引的函数。要设置索引,可以使用简单的赋值
df=pd.DataFrame(index=[0], columns=[1,2,3],data=[[1,2,3]])
df
1 2 3
0 1 2 3
anio=2001
df.index=[anio]
df
1 2 3
2001 1 2 3
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html
set_index
期望keys
参数为label or array-like or list of labels/arrays
。您告诉它使用标记为2001
的索引(如anio
=2001
)
试题:
maximosVerano.set_index("anio", inplace=True)
或
maximosVerano.set_index(["anio"], inplace=True))