我有以下数据框:
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/