在将索引设置为DataFrame时,如何避免“KeyError:[2001]中的任何一个都不在列”中?

2024-09-20 00:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为DataFramemaximoVeranoDataFrame并希望重新对其进行索引,因为我将用不同的年份索引附加其他数据帧。但是,当我想使用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:\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? 请注意,索引的类型最初是一个范围。也许问题就在那里,但我不确定


Tags: columnsoftheincorenone示例dataframe
2条回答

试试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。您告诉它使用2002列作为索引(如anio=2001

尝试:

maximosVerano.set_index("anio", inplace=True)

maximosVerano.set_index(["anio"], inplace=True))

相关问题 更多 >