Example of using sort_values ​​isin in pandas DataFrame

零下一度
Release: 2017-05-25 11:16:46
Original
4668 people have browsed it

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  3
Copy after login

At 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
Copy after login

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
Copy after login
[Related recommendations]

1.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!