【问题标题】:Pandas Columns with Date and Time - How to sort?带有日期和时间的 Pandas 列 - 如何排序?
【发布时间】:2020-10-01 14:22:47
【问题描述】:

我已经将几个csv files 连接到one dataframe 中以形成combined csv file。但是columns 之一在采用converted to date_time 格式后同时具有datetime (e.g 02:33:01 21-Jun-2018)。但是当我打电话时

new_dataframe = old_dataframe.sort_values(by = 'Time')

它按时间对数据帧进行排序,完全忽略日期。

Index                   Time   Depth(ft)  Pit Vol(bbl)  Trip Tank(bbl)
189147  00:00:00 03-May-2018   2283.3578      719.6753         54.2079
3875    00:00:00 07-May-2018   5294.7308     1338.7178         29.5781
233308  00:00:00 20-May-2018   8073.7988      630.7964         41.3574
161789  00:00:01 05-May-2018    122.2710      353.6866         58.9652
97665   00:00:01 01-May-2018  16178.8666      769.1328         66.0688

如何让它先按日期排序,然后按时间排序,以便 Aprils 天数在前,然后在 chronological order 中?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    为了先使用date 再使用time 进行排序,您的Time 列应该是正确的Date followed by Time。目前正好相反。

    你可以这样做:

    df['Time'] = df['Time'].str.split(' ').str[::-1].apply(lambda x: ' '.join(x))
    
    df['Time'] = pd.to_datetime(df['Time'])
    

    现在按Time 对您的 df 进行排序,如下所示:

    df.sort_values('Time')
    

    【讨论】:

    • 那个排序了,没看出是走错路了。
    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 2021-12-09
    • 2023-02-07
    • 1970-01-01
    • 2016-08-09
    • 2017-02-01
    • 2022-12-01
    • 1970-01-01
    相关资源
    最近更新 更多