更改多列中整个列中日期的格式

问题描述 投票:2回答:1

我有一个数据集,说:

DateJoined      Name       Number      DateLeft

11/03/2015      Tom        001199      11/03/2019
11/03/2016      Bil        001197      12/03/2019
11/03/2017      Mat        001196      13/03/2019
11/03/2018      Jon        001195      14/03/2019

我只想选择具有日期的列,并将该列中所有日期的格式更改为月/日/年。

我已经尝试过像这样的代码,但它会出现错误。

date_cols=[col for col in dataset.columns if 'date' in col]
for col in dataset[date_cols]:
  for row in dataset[date_cols]:
   dataset[date_cols]=pd.to_datetime(dataset[date_cols]).dt.strftime('%d-%m-%Y')
   next(row)
next(col)

任何帮助,将不胜感激。我还是熊猫和蟒蛇的新手

python-3.x pandas
1个回答
0
投票

你不需要循环 - 使用filter

s=df.filter(like='Date').apply(pd.to_datetime,dayfirst=True)
df[s.columns]=s
df
  DateJoined Name  Number   DateLeft
0 2015-03-11  Tom    1199 2019-03-11
1 2016-03-11  Bil    1197 2019-03-12
2 2017-03-11  Mat    1196 2019-03-13
3 2018-03-11  Jon    1195 2019-03-14
© www.soinside.com 2019 - 2024. All rights reserved.