You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Pandas DataFrame的日期时间列排序?sort_values未生效解决

Why Your sort_values Isn't Working on visit_time

Hey there! The issue here is almost certainly that your visit_time column is stored as a string (object) type instead of a datetime type. When you sort strings, pandas uses lexicographical order (like dictionary order) rather than actual chronological time order—which is why your sort isn't producing the result you expect.

Let's walk through how to fix this step by step:

Step 1: Verify the Data Type

First, confirm the type of your visit_time column with this command:

print(camp_data['visit_time'].dtype)

If it outputs object, that confirms it's stored as strings.

Step 2: Convert to Datetime Type

Use pandas' pd.to_datetime() function to convert the column to a proper datetime format. Your time strings follow the standard YYYY-MM-DD HH:MM:SS format, so pandas should parse them automatically:

camp_data['visit_time'] = pd.to_datetime(camp_data['visit_time'])

If you had a non-standard format, you could add a format parameter (e.g., format="%Y-%m-%d %H:%M:%S"), but it's not needed here.

Step 3: Sort the DataFrame

Now that the column is datetime type, your sort will work as expected. You can either create a sorted copy of the DataFrame:

camp_data_sorted = camp_data.sort_values(by=['visit_time'])

Or modify the original DataFrame in place:

camp_data.sort_values(by=['visit_time'], inplace=True)

Example Walkthrough

Let's test this with your sample data:

import pandas as pd

# Recreate your sample data
data = {
    'id': [39697, 39701, 39708, 39711, 39715, 39717, 39718],
    'visit_time': [
        '2017-12-25 16:19:51',
        '2017-12-25 16:19:48',
        '2017-12-25 16:19:19',
        '2017-12-25 16:19:18',
        '2017-12-25 16:19:32',
        '2017-12-25 16:19:57',
        '2017-12-25 16:19:19'
    ]
}
camp_data = pd.DataFrame(data)

# Check initial type (object)
print("Original dtype:", camp_data['visit_time'].dtype)

# Convert to datetime
camp_data['visit_time'] = pd.to_datetime(camp_data['visit_time'])

# Check updated type (datetime64[ns])
print("Updated dtype:", camp_data['visit_time'].dtype)

# Sort and print result
camp_data_sorted = camp_data.sort_values(by=['visit_time'])
print("\nSorted DataFrame:")
print(camp_data_sorted)

Expected Output

The sorted DataFrame will now be ordered chronologically:

id          visit_time
3  39711 2017-12-25 16:19:18
2  39708 2017-12-25 16:19:19
6  39718 2017-12-25 16:19:19
4  39715 2017-12-25 16:19:32
1  39701 2017-12-25 16:19:48
0  39697 2017-12-25 16:19:51
5  39717 2017-12-25 16:19:57

That's it! Converting the column to datetime ensures pandas understands the chronological order, making your sort work correctly.

内容的提问来源于stack exchange,提问作者user3100568

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:32:59