For more information on concepts covered in this lesson, you can check out Sorting Data With Python.
Using Sort Methods to Modify Your DataFrame
00:13 That’s because sorting in pandas doesn’t work in-place by default. In general, this is the most common and preferred way to analyze your data with pandas since it creates a new DataFrame, instead of modifying the original.
This allows you to preserve the state of the data from when you read it from the file. However, you can modify the original DataFrame directly by specifying the optional parameter
inplace with the value of
inplace set to
True, you’re modifying the original DataFrame, so the sort methods return
NaN. Sort your DataFrame by the values of the
city08 column like the very first example, but with
inplace set to
True, as seen on-screen.
Notice that calling
.sort_values() doesn’t return a DataFrame. Here’s what the original DataFrame looks like. In the DataFrame object, the values are now sorted in ascending order, based on the
It’s generally a good idea to avoid using
inplace=True for analysis because the changes to your DataFrame can’t be undone. The next example illustrates that
inplace also works with
If you’re familiar with Python’s built-in functions
sorted(), then the
inplace parameter available in the pandas sort methods might seem familiar. For more information, check out this Real Python course.
Become a Member to join the conversation.