[英]Value error while unpacking .split() method on string of time values
我有下面的array Object
,它基本上是以小時、分鍾和秒為單位的時間。 我想將此 object 轉換為幾分鍾,但出現錯誤。 該錯誤似乎是由於解包.split
方法結果時字符串長度不同造成的。 有什么建議么?
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)
看看前幾行。 假設第二行17:34
。 這就是你拆分它時發生的情況。
In [1]: "17:34".split(":")
Out[1]: ['17', '34']
如您所見,只有 2 個值,因為您只有一個:
並且您試圖將其解壓縮為 3 個變量h,m,s
無法完成的事情。
您有多種選擇來克服這個問題。
17:34
-> 0:17:34
values = i.split(':')
if len(values) == 2:
h = 0
m,s = values
else:
h,m,s = values
您可以添加0:
如果通過Series.mask
和Series.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
詳情:
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
使用這個答案的一點點輸入,您還可以獲得時間戳的總秒數
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
請注意,即使時間字符串中僅提供秒(沒有分鍾或小時),這也有效。 當然,如果您想要分鍾,您可以包含/ 60
。 您可以將 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.