我有一個資料集,我想在其中減少日期列以顯示 YY 與 YYYY
資料
ID Date Stat
AMS101 Q1.2022 y
BWI101 Q1.2022 y
BWI101 Q1.2022 n
期望的
ID Date Stat
AMS101 Q1.22 y
BWI101 Q1.22 y
BWI101 Q1.22 n
正在做
df['Date'] = df['Date'].astype(datetime).datetime[:-2]
任何建議表示贊賞
uj5u.com熱心網友回復:
嘗試這個:
df['Date'] = df['Date'].astype(str).apply(lambda x: str(x[0:3]) str(x[-2:]))
uj5u.com熱心網友回復:
避免使用apply,最好在這里使用正則運算式:
df['Date'] = df['Date'].astype(str).str.replace(r'\.\d{2}', '.')
或者,如果 Date 已經是一個字串:
df['Date'] = df['Date'].str[:3] df['Date'].str[-2:]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429566.html
