【问题标题】:dealing with dates in pandas处理 pandas 中的日期
【发布时间】:2022-08-08 06:15:38
【问题描述】:

我在 DataFrame 中有主要由日期组成的列。 但也可能有字符串或空值。 我想从列中提取年份,但由于字符串值而出错。 有没有办法对此应用通用解决方案?不仅要获得一年或一个月,还要应用可能以此错误结束的其他功能。 我的意思是,我想了解这个问题的性质以及如何处理它。

代码就像

dates={\'date\':[\'11/03/2019\',\'12/05/2021\',\'\',\'11/03/2021\',\'x\'],
      \'date2\':[\'11/04/2019\',\'12/03/2021\',\'11/06/2021\',np.nan,\'ab\'],
}
df2=pd.DataFrame(dates)
df2[\'year\'] =pd.DatetimeIndex(df2[\'date\']).year
the error messages

未知字符串格式:x

先感谢您!

    标签: python pandas string date


    【解决方案1】:

    你可以试试这个

    dates={'date':['11/03/2019','12/05/2021','','11/03/2021','x'],
          'date2':['11/04/2019','12/03/2021','11/06/2021',np.nan,'ab'],
    }
    df =pd.DataFrame(dates)
    df["date"] = pd.to_datetime(df['date'], errors = "coerce")
    df["date2"] = pd.to_datetime(df['date2'], errors = "coerce")
    
    df["year1"] = df["date"].dt.year
    df["year2"] = df["date2"].dt.year
    

    输出 -

    date date2 year1 year2
    0 2019-11-03 00:00:00 2019-11-04 00:00:00 2019.0 2019.0
    1 2021-12-05 00:00:00 2021-12-03 00:00:00 2021.0 2021.0
    2 NaT 2021-11-06 00:00:00 nan 2021.0
    3 2021-11-03 00:00:00 NaT 2021.0 nan
    4 NaT NaT nan nan

    如果您不希望数据框中有任何空值,请在添加 year1year2 列之前执行 df.dropna(inplace = True)

    【讨论】:

      【解决方案2】:

      你可以试试这个:请注意代码中的符号“le”对应于“len”

      df2 = pd.DataFrame(日期) df2['year'] = [e[6:] if le(e) == 10 else None for e in df2['date']] df2

      Here is the output

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-08
        • 1970-01-01
        • 2020-01-05
        • 2012-08-05
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多