简体   繁体   中英

python convert a column's datetime format

below is my df

df = pd.DataFrame({
                   'Year': [2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031,2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040],
                    'Count' : [1, 9, 8, 1, 6, 5, 6, 2, 4, 1, 1, 1, 6, 1, 4, 3, 8, 8, 2, 4]
})

I want to convert all Years to 1st of March of that year, ie 2021 will be replaced by 1/3/2021, 2022 by 1/3/2022 and so on. Whats the quickest way to do that?

Because default date format is YYYY-MM-DD add -03-01 and convert to datetimes:

df['date'] = pd.to_datetime(df.Year.astype(str) + '-03-01')
print (df)

    Year  Count       date
0   2021      1 2021-03-01
1   2022      9 2022-03-01
2   2023      8 2023-03-01
3   2024      1 2024-03-01
4   2025      6 2025-03-01
5   2026      5 2026-03-01
6   2027      6 2027-03-01
7   2028      2 2028-03-01
8   2029      4 2029-03-01
9   2030      1 2030-03-01
10  2031      1 2031-03-01
11  2032      1 2032-03-01
12  2033      6 2033-03-01
13  2034      1 2034-03-01
14  2035      4 2035-03-01
15  2036      3 2036-03-01
16  2037      8 2037-03-01
17  2038      8 2038-03-01
18  2039      2 2039-03-01
19  2040      4 2040-03-01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM