使用无转换为日期时间

时间:2019-08-19 12:52:12

标签: python pandas datetime

我有一个字符串类型的变量,实际上是一个时间。该系列包含一些None值。

d = {'col1': [1,2,3,4,5,6], 'time': ['07:00:00','07:30:00','07:00:00',None,'08:00:00','09:00:00']}
data = pd.DataFrame(data=d)

我想创建一个新列并提取小时和分钟值(而不是秒)。 预期输出为:

'new_col ': ['07:00','07:30','07:00',None,'08:00','09:00']
#instead of None I could also have NaT

以下两个无效。.

data['new_col']= data['time'].dt.hour
data['new_col']= np.where(data['time'].notna(),data['time'].hour,None)
  

AttributeError:“系列”对象没有属性“小时”

data['new_col']= np.where(data['time'].notna(),data['time'].apply(lambda x: dt.strptime(x, '%H:%M'),None))

这给了我:

  

ValueError:未转换的数据保留::00

2 个答案:

答案 0 :(得分:1)

dt.strftime('%H:%M')都运行良好之后,出现了以下情况:

data['new_col'] = pd.to_datetime(data['time']).dt.strftime('%H:%M')
print (data)
   col1      time new_col
0     1  07:00:00   07:00
1     2  07:30:00   07:30
2     3  07:00:00   07:00
3     4      None     NaT
4     5  08:00:00   08:00
5     6  09:00:00   09:00

但是如果有测试值,则没有None,没有缺失值,只有字符串NaT

print (data['new_col'].tolist())
['07:00', '07:30', '07:00', 'NaT', '08:00', '09:00']

因此需要将NaT替换为NaNNone

data['new_col'] = pd.to_datetime(data['time']).dt.strftime('%H:%M').replace('NaT', np.nan)
print (data['new_col'].tolist())
['07:00', '07:30', '07:00', nan, '08:00', '09:00']

data['new_col'] = (pd.to_datetime(data['time'])
                     .dt.strftime('%H:%M')
                     .mask(lambda x: x=='NaT', None))

或者:

data['new_col']= np.where(data['time'].notna(),
                          pd.to_datetime(data['time']).dt.strftime('%H:%M'),
                          None)

print (data)
   col1      time new_col
0     1  07:00:00   07:00
1     2  07:30:00   07:30
2     3  07:00:00   07:00
3     4      None    None
4     5  08:00:00   08:00
5     6  09:00:00   09:00

print (data['new_col'].tolist())
['07:00', '07:30', '07:00', None, '08:00', '09:00']

替代:

data['new_col'] = data['time'].str.rsplit(':', n=1).str[0]
print (data)
   col1      time new_col
0     1  07:00:00   07:00
1     2  07:30:00   07:30
2     3  07:00:00   07:00
3     4      None    None
4     5  08:00:00   08:00
5     6  09:00:00   09:00

print (data['new_col'].tolist())
['07:00', '07:30', '07:00', None, '08:00', '09:00']

答案 1 :(得分:1)

我认为

data['new_col'] = pd.to_datetime(data['time']).dt.strftime('%H:%M')

提供所需的输出(或关闭)?

首先,使用data.timedatetime64[ns]转换为pd.to_datetime类型。这样一来,您就可以使用.dt访问器来执行各种与日期时间相关的操作。