【问题标题】:Convert dataframe column to datetime only if length of string is not zero仅当字符串长度不为零时才将数据框列转换为日期时间
【发布时间】:2020-08-13 10:40:09
【问题描述】:

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

到目前为止我已经尝试过:

选项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"]

})

【问题讨论】:

  • 在数据框中显示数据
  • pd.to_datetime(df['etime'],errors='ignore') 是做什么的?
  • @Manakin -> 它只是在适用的行上转换为日期时间,但不进行格式化 ''%Y-%m-%d %H:%M''

标签: python python-3.x pandas dataframe python-datetime


【解决方案1】:

两步,

首先让我们使用您的日期时间创建一个系列并将错误值强制转换为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 处小时列中的拼写错误。

【讨论】:

  • 谢谢@manakin,是的,索引 3 是一个错字,我现在已经更正了。
【解决方案2】:

你可以试试这样的:

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

【讨论】:

  • 试过这个,它给了我一个错误 ===> 'AttributeError: 'str' object has no attribute 'str'
  • 现在试试,没有数据我无法测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2021-12-30
  • 2015-04-25
  • 2015-09-17
  • 1970-01-01
  • 2016-01-28
  • 2016-12-15
相关资源
最近更新 更多