我正在尝试阅读该专栏total_time
并总结用户具有相同含义的时间'name 1' = 03:30 + 04:00
,依此类推,我正在尝试使用pandas,并且设法将数据分开,但是当我尝试使用时total_time
,因为一个对象,我不能仅仅sum
把它设置起来,所以我试图将这个对象的格式更改为一个datetime
对象,但是我却做不到。
format_time="%H:%M"
user1 = df.loc[df['user']== "name 1"]
user1['hora']=datetime.strptime((user1['total_time']),format_time)
我已经尝试过了,这给了我一个错误
AttributeError: module 'datetime' has no attribute 'strptime'
.strptime
正确的名称空间访问的事实外,它应该是,即使使用正确的函数调用datetime.datetime.strptime
,实现也会导致错误(TypeError: strptime() argument 1 must be str, not Series
)。
pandas
已经具有内置的矢量化日期时间功能。'total_time
表示绝对时间,因此应使用转换列pandas.to_timedelta
。
string
形式'hh:mm:ss'
,因此df.tt + ':00'
用于将'total_time'
('tt'
)列转换为正确的格式。import pandas as pd
# test dataframe
df = pd.DataFrame({'user': ['n1', 'n2', 'n3', '', 'n1', 'n2'],
'ts': ['09:30', '09:30', '09:30', '', '14:00', '10:00'],
'te': ['14:00', '10:00', '12:00', '', '18:00', '18:00'],
'ls': ['12:00', '', '', '', '', '13:00'],
'le': ['13:00', '', '', '', '', '14:00'],
'tt': ['03:00', '00:30', '02:30', '00:00', '04:00', '07:00']})
# display(df)
user ts te ls le tt
0 n1 09:30 14:00 12:00 13:00 03:00
1 n2 09:30 10:00 00:30
2 n3 09:30 12:00 02:30
3 00:00
4 n1 14:00 18:00 04:00
5 n2 10:00 18:00 13:00 14:00 07:00
# fill blanks with nan
df = df.replace('', np.nan)
# drop all rows that are all nan, except total_time
df = df.dropna(axis=0, how='all', subset=df.columns[:-2])
# display(df)
user ts te ls le tt
0 n1 09:30 14:00 12:00 13:00 03:00
1 n2 09:30 10:00 NaN NaN 00:30
2 n3 09:30 12:00 NaN NaN 02:30
4 n1 14:00 18:00 NaN NaN 04:00
5 n2 10:00 18:00 13:00 14:00 07:00
# convert total_time (tt) to a timedelta
df.tt = pd.to_timedelta(df.tt + ':00')
# groupby user and sum the tt column
total_hours = df.groupby('user').tt.sum().reset_index(name='total_hours')
# display(total_hours)
user total_hours
0 n1 0 days 07:00:00
1 n2 0 days 07:30:00
2 n3 0 days 02:30:00
# to have total_hours as a float
total_hours.total_hours = total_hours.total_hours / pd.to_timedelta(1, 'h')
# display(total_hours)
user total_hours
0 n1 7.0
1 n2 7.5
2 n3 2.5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句