【问题标题】:Combining year, month, day columns into a single date column with pandas [duplicate]用熊猫将年、月、日列组合成一个日期列[重复]
【发布时间】:2019-02-20 20:23:01
【问题描述】:

我在合并数据时一直遇到错误:

record_id   month   day year   sex
1              7    17  1977    M
2              7    15  1979    M
3              7    26  1978    F
4              7    16  1973    M

我尝试了将月份、日期和年份组合成一列的不同方法:

1. surveys_df['date'] = surveys_df['month'].astype(str) + surveys_df['day'] + surveys_df['year']
2. surveys_df['Date'] = pd.to_datetime(surveys_df[['month', 'day', 'year']])

3. r= pd.to_datetime(surveys_df[['year', 'month', 'day']])

4. surveys_df['date'] = pd.to_datetime(surveys_df[['day','month','year']])

我得到的错误:

ValueError:无法组合日期时间:日期超出范围 天

我知道我可以使用 error= 'coerce' 来强制执行此操作,但我想避免使用该方法。

【问题讨论】:

  • pd.to_datetime(df[['day','month','year']], dayfirst=True) ?不确定pd.to_datetime 在 python2 中的工作原理。也许你有一个非常旧的熊猫版本?
  • minimal reproducible example 会很有帮助,事实上,如果您能够提供这样的示例,解决方案可能会变得显而易见。
  • @jpp 因此,OP 提供minimal reproducible example 的要求并不高,我已将此标记为一个更好的帖子的欺骗。
  • 嗨,如果它返回 KeyError: "['year'] not in index" 怎么办?谢谢

标签: python pandas python-2.7 datetime dataframe


【解决方案1】:
pd.to_datetime(df[['year', 'month', 'day']])

0   1977-07-17
1   1979-07-15
2   1978-07-26
3   1973-07-16
dtype: datetime64[ns]

如果有您想要 NaTify 的无效组合,则添加 errors='coerce' 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 2018-04-21
    • 2019-09-10
    • 2020-12-21
    • 2021-08-31
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多