gpt4 book ai didi

python - 尝试访问 Pandas 数据框中新分配的列时出现 KeyError

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:52 25 4
gpt4 key购买 nike

KeyError 帖子上的解决方案都没有解决我的问题,因此这个问题:

我在 Pandas DataFrame 中有以下列:

df['EventDate']

0 26-12-2016
1 23-12-2016
2 16-12-2016
3 15-12-2016
4 11-12-2016
5 10-12-2016
6 07-12-2016

现在我尝试使用以下命令拆分日期并将年份的最后四个值提取到另一个系列中:

trial=df["EventDate"].str.split("-",2,expand=True)

现在使用第 3 个索引值,我可以获得整个值:

df.year=trial[2]

现在检查年份列的数据类型:

type(df.year)
Out[80]: pandas.core.series.Series

是的,它是通过 trial[2] 代码转移到 df.year 的 Pandas 系列

print(trial[2])
0 2016
1 2016
2 2016
3 2016
4 2016

现在我正在尝试按年份列分组,这就是我收到错误的地方:

yearwise=df.groupby('year')

Traceback (most recent call last):

File "<ipython-input-81-cf39b80933c4>", line 1, in <module>
yearwise=df.groupby('year')

File "C:\WINPYTH\python-3.5.4.amd64\lib\site-
packages\pandas\core\generic.py", line 4416, in groupby
**kwargs)

File "C:\WINPYTH\python-3.5.4.amd64\lib\site-
packages\pandas\core\groupby.py", line 1699, in groupby
return klass(obj, by, **kwds)

File "C:\WINPYTH\python-3.5.4.amd64\lib\site-
packages\pandas\core\groupby.py", line 392, in __init__
mutated=self.mutated)

File "C:\WINPYTH\python-3.5.4.amd64\lib\site-
packages\pandas\core\groupby.py", line 2690, in _get_grouper
raise KeyError(gpr)

KeyError: 'year'

能否请您帮助解决此 KeyError 并获取 Year 列的 Groupby 值?

非常感谢您的回答。

最佳答案

这里最根本的误解是你以为在做

df.year = ...

df 中创建一个名为 year 的列,但这是真的!观察:

print(df)

Col1
0 26-12-2016
1 23-12-2016
2 16-12-2016
3 15-12-2016
4 11-12-2016
5 10-12-2016
6 07-12-2016

df.year = df.Col1.str.split('-', 2, expand=True)[2]

print(type(df.year))
pandas.core.series.Series

print(df) # where's 'year'??

Col1
0 26-12-2016
1 23-12-2016
2 16-12-2016
3 15-12-2016
4 11-12-2016
5 10-12-2016
6 07-12-2016

那么,df.year 是什么?它是df 的一个属性,与列不同。在 python 中,您可以使用 dot 表示法分配属性,因此这不会引发错误。您可以通过打印出 df.__dict__ 来确认:

print(df.__dict__)

{ ...
'year': 0 2016
1 2016
2 2016
3 2016
4 2016
5 2016
6 2016
Name: 2, dtype: object}

如果你想实际分配给一个列,你需要使用 [...] 索引语法,如下所示:

df['year'] = df.Col1.str.split('-', 2, expand=True)[2]
print(df)

Col1 year
0 26-12-2016 2016
1 23-12-2016 2016
2 16-12-2016 2016
3 15-12-2016 2016
4 11-12-2016 2016
5 10-12-2016 2016
6 07-12-2016 2016

关于python - 尝试访问 Pandas 数据框中新分配的列时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45912419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com