简体   繁体   English

对时间值字符串进行 unpacking.split() 方法时出现值错误

[英]Value error while unpacking .split() method on string of time values

I have the below array Object which is essentially time in hours, minutes and seconds.我有下面的array Object ,它基本上是以小时、分钟和秒为单位的时间。 I want to convert this object into minutes but am getting an error.我想将此 object 转换为几分钟,但出现错误。 The error seem to be due to different string lengths while unpacking .split method result.该错误似乎是由于解包.split方法结果时字符串长度不同造成的。 Any suggestions?有什么建议么?

df6['Chip Time']
0         16:42
1         17:34
2         18:13
3         18:32
4         19:12
         ...   
1453    1:35:08
1454    1:43:41
1455    1:45:36
1456    1:45:40
1457    1:48:13
Name: Chip Time, Length: 1458, dtype: object

time_list = df6['Chip Time'].tolist()
# You can use a for loop to convert 'Chip Time' to minutes
time_mins = []
for i in time_list:
    h,m,s = i.split(':')
    math = (int(h)*3600+int(m)*60+int(s))/60
    time_mins.append(math)
print(time_mins)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-52-ac7d4ab91169> in <module>
      3 time_mins = []
      4 for i in time_list:
----> 5     h,m,s = i.split(':')
      6     math = (int(h)*3600+int(m)*60+int(s))/60
      7     time_mins.append(math)

ValueError: not enough values to unpack (expected 3, got 2)

Take a look at the first few rows.看看前几行。 Let's say 2nd row 17:34 .假设第二行17:34 This is what happens when you split it.这就是你拆分它时发生的情况。

In [1]: "17:34".split(":")
Out[1]: ['17', '34']

As you can see there are only 2 values because you have only one : and you are trying to unpack it to 3 variables h,m,s what can not be done.如您所见,只有 2 个值,因为您只有一个:并且您试图将其解压缩为 3 个变量h,m,s无法完成的事情。

You have several options to overcome this problem.您有多种选择来克服这个问题。

  1. You could format your data differently and always include hours so 17:34 -> 0:17:34您可以以不同的方式格式化数据并始终包含小时数,因此17:34 -> 0:17:34
  2. You could handle 2 cases in your parser您可以在解析器中处理 2 个案例
values = i.split(':')
if len(values) == 2:
    h = 0
    m,s = values
else:
   h,m,s = values
  1. You could use regex but I would not recommend it as it is less readable then other options您可以使用正则表达式,但我不推荐它,因为它的可读性不如其他选项

You can add 0: if length of strins is 5 by Series.mask and Series.str.len , then connvert column to timedeltas by to_timedelta , get seconds by Series.dt.total_seconds and divide 60 :您可以添加0:如果通过Series.maskSeries.str.len的字符串长度为5 ,则通过Series.dt.total_seconds将列转换为 timedeltas,通过to_timedelta获得秒数并除以60

s = df6['Chip Time'].mask(df6['Chip Time'].str.len().eq(5), '0:' + df6['Chip Time'])
df6['min'] = pd.to_timedelta(s).dt.total_seconds() / 60
print (df6)
     Chip Time         min
0        16:42   16.700000
1        17:34   17.566667
2        18:13   18.216667
3        18:32   18.533333
4        19:12   19.200000
1453   1:35:08   95.133333
1454   1:43:41  103.683333
1455   1:45:36  105.600000
1456   1:45:40  105.666667
1457   1:48:13  108.216667

Details :详情

print (s)
0       0:16:42
1       0:17:34
2       0:18:13
3       0:18:32
4       0:19:12
1453    1:35:08
1454    1:43:41
1455    1:45:36
1456    1:45:40
1457    1:48:13
Name: Chip Time, dtype: object

using a little bit of input from this answer , you could also obtain the total seconds of your timestamps as使用这个答案的一点点输入,您还可以获得时间戳的总秒数

def timestring_to_seconds(ts, sep=':'):  
    return sum(x * int(t) for x, t in zip((1,60,3600), reversed(ts.split(sep))))

ts = '00:04:23'
print(timestring_to_seconds(ts))
# 263

ts = '04:23'
print(timestring_to_seconds(ts))
# 263

ts = '23'
print(timestring_to_seconds(ts))
# 23

Note that this works even if there are only seconds (no minutes or hours) provided in the timestring.请注意,即使时间字符串中仅提供秒(没有分钟或小时),这也有效。 Of course you can include / 60 if you want minutes instead.当然,如果您想要分钟,您可以包含/ 60 And you can map the function to a df column:您可以将 map 将 function 移至df列:

import pandas as pd
df = pd.DataFrame({'Chip Time': ['00:04:23', '04:23', '23']})
df['s'] = df['Chip Time'].map(timestring_to_seconds)
# df
#   Chip Time    s
# 0  00:04:23  263
# 1     04:23  263
# 2        23   23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM