简体   繁体   English

如何解决为什么出现在 Pandas 中的 KeyError

[英]How to to solve why this KeyError that is appearing in Pandas

I'm using Pandas to process the Dataframe, I need to use the Date column to create additional columns:我正在使用 Pandas 处理数据框,我需要使用Date列来创建其他列:

I have filtered the Date column to get 2022/2021 information only using:我已过滤Date列以仅使用以下方法获取 2022/2021 信息:

df = df.loc[df["Date"].between("2022", "2021")]

Currently I have:目前我有:

Date日期 Type类型 Initial最初的 Number数字
2022 2022 Bin垃圾桶 S小号 5 5
2022 2022 Bin垃圾桶 S小号 6 6
2022 2022 Bin垃圾桶 S小号 9 9
2021 2021 Bin垃圾桶 B 5 5
2021 2021 Bin垃圾桶 B 7 7
2021 2021 Bin垃圾桶 B 0 0

I am currently trying to get the following output:我目前正在尝试获得以下输出:

Type类型 2022 2022 2021 2021 Initial最初的 Difference区别
Bin垃圾桶 20 20 12 12 S/B S/B 8 8

Following the process to create the bottom table, I have come across the following error按照创建底表的过程,我遇到了以下错误

df = df.loc[df["Date"].between("2022", "2021")]
dfx = df.groupby(['Type ','Date ']).agg({'Initial ':lambda x: '/'.join([str(r) for r in x.unique()]),'Number':'sum'}).reset_index()
dfy = dfx.pivot(index=['Type ','Initial '], columns='Date ', values='Number').reset_index()

but I keep receiving the following error message:但我不断收到以下错误消息:

  raise KeyError(key) from err
KeyError: 'Date'

The KeyError: 'Date' doesn't have a space in it. KeyError: 'Date'中没有空格。 this is the only line I see where Data doesn't have a trailing space.这是我看到的唯一一行Data没有尾随空格。

df = df.loc[df["Date"].between("2022", "2021")]

Try adding a trailing space and see what happens:尝试添加尾随空格,看看会发生什么:

df = df.loc[df["Date "].between("2022", "2021")]

Like @topsail says, trailing spaces in column names are a recipe for errors,就像@topsail 所说,列名中的尾随空格是错误的根源,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM