【问题标题】:TypeError: strptime() argument 1 must be string, not SeriesTypeError: strptime() 参数 1 必须是字符串,而不是系列
【发布时间】:2017-10-14 04:12:47
【问题描述】:

我正在从数据框的列中写入单个条目

2011100101 被解释为 2011 年 10 月 1 日凌晨 1 点。

我希望它的格式更改为 YYYY-Mmm-dd HH

train['date1']=datetime.strptime(train['ID'], '%Y%m%d%H')

但出现错误 TypeError: strptime() argument 1 must be string, not Series

如何将单个列中的整个条目更改为所需的格式?

【问题讨论】:

  • 尝试打印train['ID'] 的内容,你会明白为什么... ;)
  • 你应该使用pd.to_datetime()

标签: python datetime


【解决方案1】:

你可以使用apply()方法

train['date1'] = train['ID'].apply(lambda x: datetime.strptime(x, '%Y%m%d%H'))

【讨论】:

  • 或列表理解:train['date1'] = [datetime.strptime(x, '%Y%m%d%H') for x in train['ID'] ]
  • 列表理解看起来更好
  • 三年后,@Accccumulation 的列表理解回答 FTW(反正对我来说)
猜你喜欢
  • 1970-01-01
  • 2018-09-04
  • 2017-01-28
  • 2016-09-02
  • 2020-07-11
  • 2019-07-07
  • 2015-06-11
  • 1970-01-01
  • 2022-11-21
相关资源
最近更新 更多