【问题标题】:How to avoid "KeyError: 'None of [2001] are in the columns'" when setting index to pandas DataFrame?将索引设置为pandas DataFrame时如何避免“KeyError:'None of [2001] are in the columns'”?
【发布时间】:2021-07-29 18:10:19
【问题描述】:

我有一个名为 maximoVeranoDataFrame 并想重新索引它,因为我将附加具有不同年份索引的其他 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


【解决方案1】:

试试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

【讨论】:

  • 您没有从您的回答中展示该技术。更改答案以匹配演示。
  • 此解决方案有效。但是我还是不明白为什么我不能使用set_index
  • @JedMitten 我不明白你的批评。 anio 显然是一个变量,其值为2001,来自问题中发布的错误。所以我的回答演示了如何使用数值设置单行数据帧索引。为了清楚起见,我进行了编辑
  • @CedricZoppolo 该函数用于将 现有列 设置为新索引。例如,如果您调用了set_index('demanda'),那么demanda 列将被设置为数据帧的索引。因为您正在尝试分配一个新值,所以这不是在您的情况下使用的方法
【解决方案2】:

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))

【讨论】:

  • 这假设"anio"maximosVerano.columns 中找到
  • 此建议无效。它显示相同的错误消息
  • “假设在 maximosVerano.columns 中找到了“anio””,这正是抛出 KeyError 的原因。因为该变量的值不存在于列中。此外,“您告诉它使用第 2002 列作为索引”是不正确的。它试图找到一个标记为2001 的列并将其设置为索引。它是命名的,而不是位置的
  • @G.Anderson 感谢您的更正 - 我更新以反映索引已命名,而不是位置
  • @CedricZoppolo,也许是因为您尝试了我提出的两个答案,您又得到了KeyError。在第一次set_index 操作之后,索引被更新(由于inplace=True)所以不再有一个名为anio 的列。
猜你喜欢
  • 2020-02-14
  • 2022-12-12
  • 2021-04-01
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-27
  • 2021-01-12
相关资源
最近更新 更多