這是我的資料框
df = pd.DataFrame({
'Date': ['01/05/2015', '15 Jul 2009', '21.03.12','2021.03.12']
})
Date
0 01/05/2015
1 15 Jul 2009
2 21.03.12
3 2021.03.12
我想要 yyyy-mm-dd 格式的“日期”列中的所有日期。預期輸出如下
Date
0 2015-01-05
1 2009-07-15
2 2021-03-12
3 2021-03-12
但我得到
Date
0 2015-01-05
1 2009-07-15
2 2012-03-21
3 2021-03-12
在這里,格式 21.03.12 不被識別為 yy.mm.dd 。為了糾正這個問題,我在 yy.mm.dd 格式日期前添加了“20”,這有效但不是永久解決方案。有沒有更好的解決方案?
提前致謝!
uj5u.com熱心網友回復:
我想你在這之后:
import pandas as pd
df = pd.DataFrame({
'Date': ['01/05/2015', '15 Jul 2009', '21.03.12', '2021.03.12']
})
df['Current'] = pd.to_datetime(df['Date'])
df['Desired'] = pd.to_datetime(df['Date'], yearfirst=True)
print(df)
結果:
Date Current Desired
0 01/05/2015 2015-01-05 2015-01-05
1 15 Jul 2009 2009-07-15 2009-07-15
2 21.03.12 2012-03-21 2021-03-12
3 2021.03.12 2021-03-12 2021-03-12
在'Desired'中,請注意21現在如何解釋為年份。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448049.html
