【问题标题】:Changing format of dates in the entire column for multiple columns为多列更改整列中的日期格式
【发布时间】:2019-03-25 09:50:09
【问题描述】:

我有一个数据集,比如说:

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 的新手

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    这里不需要循环——使用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
    

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2013-03-01
      • 2023-02-03
      相关资源
      最近更新 更多