gpt4 book ai didi

python - 本地化并更改 pandas 数据框中的日期

转载 作者:行者123 更新时间:2023-12-01 02:46:19 25 4
gpt4 key购买 nike

我有一个从定期更新的 Excel 文件中获取的 pandas 数据框。在一列中,我的日期为 datetime64。它不用作索引。这些条目的时间跨度从 2015 年至今。有时,人们会在输入日期时出错。所以我知道有一个条目的日期是 1945-11-05,正确的是 2015-11-05。每次更新 Excel 文件时,单元格的这一行都会发生变化,因此我无法使用行/列号对其进行本地化。我想将此单元格更新为正确的日期。我如何定位该单元格并更改年份?

数据框如下所示:

article_number order_number date         quantity
1234 abcd 2015-08-16 123
1234 xyz 2015-09-01 456
2342 qsdf 2015-01-04 12
4223 qwerty 1945-11-05 155
0815 qwertz 2016-01-01 667

最佳答案

本地化:

In [128]: df.loc[df['date'].dt.year < 2015]
Out[128]:
article_number order_number date quantity
3 4223 qwerty 1945-11-05 155

要更改:

df.loc[df['date'].dt.year < 2015, 'date'] = \
df.loc[df['date'].dt.year < 2015, 'date'].map(lambda x: x.replace(year=2015))

结果:

In [137]: df
Out[137]:
article_number order_number date quantity
0 1234 abcd 2015-08-16 123
1 1234 xyz 2015-09-01 456
2 2342 qsdf 2015-01-04 12
3 4223 qwerty 2015-11-05 155
4 815 qwertz 2016-01-01 667

关于python - 本地化并更改 pandas 数据框中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45231151/

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