python - 如何更改 dtype datetime64[ns] 的 pandas 系列的原始日期?
问题描述
我有一个 dtype datetime64[ns] 的 pandas 系列。这是它的样子:
0 1970-01-01 00:00:00
1 1970-01-01 00:00:01
2 1970-01-01 00:00:02
3 1970-01-01 00:00:03
4 1970-01-01 00:00:04
5 1970-01-01 00:00:05
6 1970-01-01 00:00:06
7 1970-01-01 00:00:07
8 1970-01-01 00:00:08
9 1970-01-01 00:00:09
10 1970-01-01 00:00:10
11 1970-01-01 00:00:11
12 1970-01-01 00:00:12
13 1970-01-01 00:00:13
14 1970-01-01 00:00:14
15 1970-01-01 00:00:15
16 1970-01-01 00:00:16
我想设置我自己的原始日期(日期时间的时间部分将保持不变),所以它看起来像这样:
0 2019-02-19 00:00:00
1 2019-02-19 00:00:01
2 2019-02-19 00:00:02
3 2019-02-19 00:00:03
4 2019-02-19 00:00:04
5 2019-02-19 00:00:05
6 2019-02-19 00:00:06
7 2019-02-19 00:00:07
8 2019-02-19 00:00:08
9 2019-02-19 00:00:09
10 2019-02-19 00:00:10
11 2019-02-19 00:00:11
12 2019-02-19 00:00:12
13 2019-02-19 00:00:13
14 2019-02-19 00:00:14
15 2019-02-19 00:00:15
16 2019-02-19 00:00:16
实现这一目标的最佳方法是什么?
解决方案
假设您的列被调用Date
,请使用Timestamp.replace
:
df['Date'].apply(lambda dt: dt.replace(2019, 2, 19))
# or more self expalantory
# df['Date'].apply(lambda dt: dt.replace(year=2019, month=2, day=19))
0 2019-02-19 00:00:00
1 2019-02-19 00:00:01
2 2019-02-19 00:00:02
3 2019-02-19 00:00:03
4 2019-02-19 00:00:04
5 2019-02-19 00:00:05
6 2019-02-19 00:00:06
7 2019-02-19 00:00:07
8 2019-02-19 00:00:08
9 2019-02-19 00:00:09
10 2019-02-19 00:00:10
11 2019-02-19 00:00:11
12 2019-02-19 00:00:12
13 2019-02-19 00:00:13
14 2019-02-19 00:00:14
15 2019-02-19 00:00:15
16 2019-02-19 00:00:16
Name: Date, dtype: datetime64[ns]
推荐阅读
- angularjs - angularjs中的半星评级
- logback - Liquibase 3.6.2 logLevel=debug 不兑现?
- jquery - 如何使用 Web Api 在 ASP.NET Core Razor 页面中创建动态菜单
- javascript - 使用 THREE.js 可缩放任何形状的轮廓
- excel - 同步 Excel 表
- reactjs - 为什么 React 必须使用 setState 进行状态更新?
- react-native - React-Native TypeError:未定义不是对象(评估'this.props.screenProps.cities.map')
- ruby-on-rails - 如何在 ruby on rails 中使用 mysql 数据库
- r - 如果代码块中有任何错误,保存 blogdown 草稿帖子(.Rmd 文件)会冻结我的 RStudio 会话
- html - 前一个 URL 未从实际 URL 中删除