我正在尝试转换'平均数字'中的数字。会话持续时间'(HH:MM:SS)列到Pandas read_csv
模块/功能中的整数(以秒为单位)。
例如,'0:03:26'将在转换后206秒。
输入示例:
Source Month Sessions Bounce Rate Avg. Session Duration
ABC.com 201501 408 26.47% 0:03:26
EFG.com 201412 398 31.45% 0:04:03
我写了一个函数:
def time_convert(x):
times = x.split(':')
return (60*int(times[0])+60*int(times[1]))+int(times[2])
只需将“0:03:26”传递给函数,此功能就可以正常工作。但是当我试图通过将函数应用到Pandas中的另一列时创建一个新的列'Duration',
df = pd.read_csv('myfile.csv')
df['Duration'] = df['Avg. Session Duration'].apply(time_convert)
它返回了一条错误消息:
> --------------------------------------------------------------------------- AttributeError Traceback (most recent call
> last) <ipython-input-53-01e79de1cb39> in <module>()
> ----> 1 df['Avg. Session Duration'] = df['Avg. Session Duration'].apply(lambda x: x.split(':'))
>
> /Users/yumiyang/anaconda/lib/python2.7/site-packages/pandas/core/series.pyc
> in apply(self, func, convert_dtype, args, **kwds) 1991
> values = lib.map_infer(values, lib.Timestamp) 1992
> -> 1993 mapped = lib.map_infer(values, f, convert=convert_dtype) 1994 if len(mapped) and
> isinstance(mapped[0], Series): 1995 from
> pandas.core.frame import DataFrame
>
> /Users/yumiyang/anaconda/lib/python2.7/site-packages/pandas/lib.so in
> pandas.lib.map_infer (pandas/lib.c:52281)()
>
> <ipython-input-53-01e79de1cb39> in <lambda>(x)
> ----> 1 df['Avg. Session Duration'] = df['Avg. Session Duration'].apply(lambda x: x.split(':'))
>
> AttributeError: 'float' object has no attribute 'split'
我不知道为什么它会说'平均值'。会话持续时间'是浮动的。
Data columns (total 7 columns):
Source 250 non-null object
Time 251 non-null object
Sessions 188 non-null object
Users 188 non-null object
Bounce Rate 188 non-null object
Avg. Session Duration 188 non-null object
% New Sessions 188 non-null object
dtypes: object(7)
有人可以帮我找出问题所在吗?
答案 0 :(得分:7)
df['Avg. Session Duration']
应该是您的函数的字符串。
df =pd.DataFrame({'time':['0:03:26']})
def time_convert(x):
h,m,s = map(int,x.split(':'))
return (h*60+m)*60+s
df.time.apply(time_convert)
这对我来说很好。
答案 1 :(得分:2)
您可以使用标准python库中的time
和datetime
将时间转换为秒:
import time, datetime
def convertTime(t):
x = time.strptime(t,'%H:%M:%S')
return str(int(datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()))
convertTime('0:03:26') # Output 206.0
convertTime('0:04:03') # Output 243.0
答案 2 :(得分:1)
错误表示该列被识别为float,而不是string。修复读取数据的方式,例如:
#!/usr/bin/env python
import sys
import pandas
def hh_mm_ss2seconds(hh_mm_ss):
return reduce(lambda acc, x: acc*60 + x, map(int, hh_mm_ss.split(':')))
df = pandas.read_csv('input.csv', sep=r'\s{2,}',
converters={'Avg. Session Duration': hh_mm_ss2seconds})
print(df)
Source Month Sessions Bounce Rate Avg. Session Duration
0 ABC.com 201501 408 26.47% 206
1 EFG.com 201412 398 31.45% 243
[2 rows x 5 columns]