仅当字符串长度不为零时才将数据框列转换为日期时间

Convert dataframe column to datetime only if length of string is not zero

我想转换一个包含日期字符串的数据框列。但在某些情况下,由于某些情况,日期字符串可能为空。所以我只想将该列中的所有其他行转换为日期时间格式,除了该特定列中可能为空的行。可能吗?

到目前为止我尝试过的:

选项 1:

df['etime'] = pd.to_datetime(df['etime'],errors='ignore').dt.strftime('%Y-%m-%d %H:%M')

选项 2:

    for ind in df.index:
        if (df['etime'].str.len()[ind] == 0) :
            df.loc[ind, 'etime'] = "----"
        else:
           df.loc[ind, 'etime'] = <need to convert this row to datetime>

请提出您的建议。

数据框示例:

data = pd.DataFrame({

    'day' : [15, 17, 20, 14, 25],

    'etime': ["20200811235205", "", "20200811215205", "20200811225205", "20200811235203"]

})

您可以尝试类似的方法:

df["etime"] =  df["etime"].apply(lambda x: pd.to_datetime(x,errors='ignore').strftime('%Y-%m-%d %H:%M') if len(x) !=0 else "----")

两步,

首先让我们用您的日期时间创建一个系列,并将错误值强制转换为 NaTs

s = pd.to_datetime(data['etime'],errors='coerce',format='%Y%m%d%H%M%S')

其次,让我们找到任何不是 NaT 的值,并将它们替换为您的目标格式。

data.loc[~s.isna(),'etime'] = s.dt.strftime('%Y-%m-%d %H:%M')

   day             etime
0   15  2020-08-11 23:52
1   17                  
2   20  2020-08-11 21:52
3   14    20200811265205
4   25  2020-08-11 23:52
  • 假设 26 是索引 3 处小时列中的拼写错误。