Home > Article > Backend Development > Example of using sort_values isin in pandas DataFrame
1. In the DataFrame of pandas, we often need to select rows with specified conditions based on a certain attribute. In this case, the isin method is particularly effective.
##
import pandas as pd df = pd.DataFrame([[1,2,3],[1,3,4],[2,4,3]],index = ['one','two','three'],columns = ['A','B','C']) print df # A B C # one 1 2 3 # two 1 3 4 # three 2 4 3At this time, suppose we select the row with a value of 1 in column A,
mask = df['A'].isin([1]) #括号中必须为list print mask # one True # two True # three False # Name: A, dtype: bool print df[mask] # A B C # one 1 2 3 # two 1 3 4
2. How to sort the DataFrame in pandas by the first keyword and the second keyword, you can use ## here #sort_values, which is sort_index in the old version.
##import pandas as pd
df = pd.DataFrame([[1,2,3],[2,3,4],[2,4,3],[1,3,7]],
index = ['one','two','three','four'],columns = ['A','B','C'])
print df
# A B C
# one 1 2 3
# two 2 3 4
# three 2 4 3
# four 1 3 7
df.sort_values(by=['A','B'],ascending=[0,1],inplace=True)
print df
# A B C
# two 2 3 4
# three 2 4 3
# one 1 2 3
# four 1 3 7
[Related recommendations]
Detailed explanation of sort() in Python How to use
2. Detailed tutorial on using values() in Python
3. Sharing examples of how to use sort in Python
The above is the detailed content of Example of using sort_values isin in pandas DataFrame. For more information, please follow other related articles on the PHP Chinese website!