gpt4 book ai didi

python - pd.to_datetime 不尊重格式

转载 作者:行者123 更新时间:2023-12-01 01:35:43 30 4
gpt4 key购买 nike

我有以下数据框:

    month     value
0 1949-01 3
1 1949-02 4
2 1949-03 5

df['month'] = pd.to_datetime(df['month'], format= '%Y/%m')

我想以以下格式获取月份:

 1949/01

但输出始终是这样的:

   month        value
0 1949-01-01 3
1 1949-02-01 4
2 1949-03-01 5

为什么它会自动添加日期并且不遵循格式?

最佳答案

这就是 pandas datetime 使用的格式。如果您愿意,可以使用dt.strftime

转换该日期时间格式
df['month'] = df['month'].dt.strftime('%Y/%m')

或者您可以采取更简单的方法开始,只需使用映射函数,无需涉及日期时间格式

df['month'] = df['month'].map(lambda x: x.replace('-', '/'))

关于python - pd.to_datetime 不尊重格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52416191/

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