如何在Python Pandas中转换值的格式以及DataFrame中的数据类型和列表中的值的格式?



我在Python Pandas中有如下的DataFrame (col1是字符串格式):

col1
-----
23.11.2020
22/12/2021
04-12-2019
....

此外,我有如下列表:

my_list = ["23.11.2020", "22/12/2021", "04-12-2019", ...]

我有两件事要做:

  1. 将df中的col1中的值转换为数据类型"datetime64"格式为"23-11-2020">
  2. 将my_list中的值转换为"23.11.2020">

所以我需要:

DataFrame如下:

col1
-----
23-11-2020
22-12-2021
04-12-2019
....

列表如下:

my_list = ["23.11.2020", "22.12.2021", "04.12.2019", ...]

如何在Python Pandas中实现?

pd.to_datetime(ser.str.replace(r"[./]", "-", regex=True), format='%d-%m-%Y').dt.strftime('%d-%m-%Y')
pd.to_datetime(pd.Series(my_list).str.replace(r"[-/]", ".", regex=True), format='%d.%m.%Y').dt.strftime('%d.%m.%Y').tolist()

相关内容

最新更新