转换和订购时间戳

时间:2018-08-03 00:48:27

标签: python pandas sorting time

我有一个时间戳的pandas df列,其中包含午夜之前的HH:MM和午夜之后的HH:MM:SS。最终,我想对这些值进行排序。

import pandas as pd

d = ({
    'A' : ['08:00','12:00','24:00:00','20:00','16:00','26:00:00'],
    })

df = pd.DataFrame(data=d)

我无法将:00添加到该列中,因为它将返回:

df['A'] = [x + ':00' for x in df['A']]

             A
0     08:00:00
1     12:00:00
2  24:00:00:00
3     20:00:00
4     16:00:00
5  26:00:00:00

我的预期输出是:

          A
0  08:00:00
1  12:00:00
4  16:00:00
3  20:00:00
2  24:00:00
5  26:00:00

5 个答案:

答案 0 :(得分:1)

使用字符串切片:

df['A'] = df['A'].str[:5] + ':00'

print(df)

          A
0  08:00:00
1  12:00:00
2  24:00:00
3  20:00:00
4  16:00:00
5  26:00:00

答案 1 :(得分:1)

在数据中24:00:01的情况下也许使用np.where

np.where(df.A.str.len()==5,df.A+':00',df.A)
Out[187]: 
array(['08:00:00', '12:00:00', '24:00:00', '20:00:00', '16:00:00',
       '26:00:00'], dtype=object)

答案 2 :(得分:0)

使用带有 str.replace 的正则​​表达式:

df.A.str.replace(r'(^\d+:\d+$)', r'\1:00')

0    08:00:00
1    12:00:00
2    24:00:00
3    20:00:00
4    16:00:00
5    26:00:00

答案 3 :(得分:0)

又一个答案(仅将秒添加到短字符串中):

df.loc[df["A"].str.len()==5, "A"] += ":00"

答案 4 :(得分:0)

即使您有类似24:00:04之类的东西(我之所以这样说,因为它不会直接将其更改为24:00:00),该方法仍然有效:

import pandas as pd

d = ({
    'A' : ['08:00','12:00','24:00:04','20:00','16:00','26:00:00'],
    })

df = pd.DataFrame(data=d)
print(df['A'].apply(lambda x: x if len(x.split(':'))==3 else x+':00'))

输出:

0    08:00:00
1    12:00:00
2    24:00:04
3    20:00:00
4    16:00:00
5    26:00:00
Name: A, dtype: object
相关问题