DataFrame按列排序求助:含重复值时sort_values方法失效
Got it, let's break down what's happening here and get your DataFrame sorted correctly. The issue you're facing is almost certainly related to how you're using the inplace=True parameter in pandas' sort_values() method.
Why Your Current Code Isn't Working
When you use inplace=True, the sort_values() method modifies your original DataFrame directly and returns None. So when you assign that result to sorted_data, you're actually setting sorted_data to None instead of the sorted DataFrame. That's why you aren't seeing your expected output!
Solution 1: Skip inplace=True (Recommended)
The cleanest approach is to let sort_values() return a new sorted DataFrame, then assign that to your variable. This keeps your original DataFrame intact:
import pandas as pd # Your original DataFrame data = pd.DataFrame({'A': [2, 3, 2], 'B': [5, 9, 7]}) # Sort and store the result in a new variable sorted_data = data.sort_values(by=['A'])
If you print sorted_data, you'll get exactly the output you want:
A B 0 2 5 2 2 7 1 3 9
Solution 2: Use inplace=True Properly
If you specifically want to modify the original DataFrame instead of creating a new one, just call the method without assigning the result (since it returns None):
data.sort_values(by=['A'], inplace=True) # Now check the original 'data' variable print(data)
This will update your original data to the sorted version.
Bonus: Ensure Exact Order with Multi-Column Sort
To guarantee that rows with duplicate values in column A are sorted by column B (matching your expected result perfectly), you can sort by both columns at once:
sorted_data = data.sort_values(by=['A', 'B'])
This way, when A values are the same, pandas will sort those rows by B in ascending order (the default behavior).
内容的提问来源于stack exchange,提问作者user3789200

