[英]How to to solve why this KeyError that is appearing in Pandas
我正在使用 Pandas 处理数据框,我需要使用Date
列来创建其他列:
我已过滤Date
列以仅使用以下方法获取 2022/2021 信息:
df = df.loc[df["Date"].between("2022", "2021")]
目前我有:
日期 | 类型 | 最初的 | 数字 |
---|---|---|---|
2022 | 垃圾桶 | 小号 | 5 |
2022 | 垃圾桶 | 小号 | 6 |
2022 | 垃圾桶 | 小号 | 9 |
2021 | 垃圾桶 | 乙 | 5 |
2021 | 垃圾桶 | 乙 | 7 |
2021 | 垃圾桶 | 乙 | 0 |
我目前正在尝试获得以下输出:
类型 | 2022 | 2021 | 最初的 | 区别 |
---|---|---|---|---|
垃圾桶 | 20 | 12 | S/B | 8 |
按照创建底表的过程,我遇到了以下错误
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()
但我不断收到以下错误消息:
raise KeyError(key) from err
KeyError: 'Date'
KeyError: 'Date'
中没有空格。 这是我看到的唯一一行Data
没有尾随空格。
df = df.loc[df["Date"].between("2022", "2021")]
尝试添加尾随空格,看看会发生什么:
df = df.loc[df["Date "].between("2022", "2021")]
就像@topsail 所说,列名中的尾随空格是错误的根源,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.