[英]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 ![]() |
Bin![]() |
S![]() |
5 ![]() |
2022 ![]() |
Bin![]() |
S![]() |
6 ![]() |
2022 ![]() |
Bin![]() |
S![]() |
9 ![]() |
2021 ![]() |
Bin![]() |
B![]() |
5 ![]() |
2021 ![]() |
Bin![]() |
B![]() |
7 ![]() |
2021 ![]() |
Bin![]() |
B![]() |
0 ![]() |
I am currently trying to get the following output:我目前正在尝试获得以下输出:
Type![]() |
2022 ![]() |
2021 ![]() |
Initial![]() |
Difference![]() |
---|---|---|---|---|
Bin![]() |
20 ![]() |
12 ![]() |
S/B ![]() |
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.