How to avoid "KeyError: 'None of [2001] are in the columns'" when setting index to pandas DataFrame?
I have a DataFrame
called maximoVerano
and want to reindex it as I will append other DataFrames with different year indexes. However when I want to use set-index
as you can see in the sample example I get the error code:
KeyError: 'None of [2001] are in the columns'
Sample code
>>> 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
Question
How can I set the index to the DataFrame
and get as index 2001 in this simple case?
Be aware that the type for the index is originally a range. Maybe the issue is there but I'm unsure.
Solution 1:
Try maximosVerano.index=[anio]
set_index()
is a function for setting a column as the new index of a dataframe. For setting the index, you can use simple assignment
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