Suppose I have a dataframe with columns
c, I want to sort the dataframe by column
b in ascending order, and by column
c in descending order, how do I do this?
df.sort_values(["a", "b"], ascending=[True, False])
You can use the ascending argument of
df.sort(["a", "b"], ascending=[True, False])
In : df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=["a","b"]) In : df1.sort(["a", "b"], ascending=[True, False]) Out: a b 2 1 4 7 1 3 1 1 2 3 1 2 4 3 2 6 4 4 0 4 3 9 4 3 5 4 1 8 4 1
As commented by @renadeen
Sort isn"t in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.
that is, if you want to reuse df1 as a sorted DataFrame:
df1 = df1.sort(["a", "b"], ascending=[True, False])
df1.sort(["a", "b"], ascending=[True, False], inplace=True)
As of pandas 0.17.0,
DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is
As such, the answer to your question would now be
df.sort_values(["b", "c"], ascending=[True, False], inplace=True)
Become a master in Python by learning coding best practices and advanced programming concepts in Python 3.7. This book is written for Python developers who wish to go further in mastering Python. A...
As information protection continues to be a growing concern for businesses today, IT security certifications have become highly desirable, even as the number of certifications has grown. Now you can s...
Data and storage models are the basis for big data ecosystem stacks. While storage model captures the physical aspects and features for data storage, data model captures the logical representation and...
The field of Artificial Intelligence (AI), which can definitely be considered to be the parent field of deep learning, has a rich history going back to 1950. While we will not cover this history in mu...