Two methods of conditional extraction with pandas (single condition, multiple conditions)

The method of conditional extraction with pandas may or may not use the query method. Consider 100 rows of data with 1-100 in column A, 101-200 in column B, and 201 to 300 in column C.

Extraction under simple conditions


df = pd.DataFrame({
    "A":[i for i in range(100)], 
    "B":[i+100 for i in range(100)], 
    "C":[i+200 for i in range(100)],])

If you don't use the method:

Extraction under simple conditions


#Extract column A less than 20
df = df[(df["A"]<20)]

python:Extraction under multiple conditions(And):


#Extract row A greater than 20 and less than 50
df = df[(df["A"]>20)&(df["A"]<50)]

Extraction under multiple conditions(Or)


#Extract column A greater than 20 or less than 50
df = df[(df["Α"]>20)|(dF["B"]<50))

For multiple conditions, you need to enclose each condition in parentheses.

When using the query method:

Extraction under a single condition:

python:Extraction under a single condition:


#Extract A less than 20
df = df.query('A< 20')

Extraction under multiple conditions(And)


df = df.query('(A > 20) and (A < 50)')

Extraction under multiple conditions(Or)


df = df.query('(A > 20) | (A < 50)')

Personally, I prefer not to use query.

[Click here if you want to get a line containing a specific string] [1] [1]:https://qiita.com/drafts/9de0ea6b7d4b7990828c

I run an app that makes money for environmental beautification activities (I will post it because Python is used in Backend). [https://play.google.com/store/apps/details?id=com.rainbowsv2.changetheworld&hl=ja][2] [2]:https://play.google.com/store/apps/details?id=com.rainbowsv2.changetheworld&hl=ja

Recommended Posts

Two methods of conditional extraction with pandas (single condition, multiple conditions)
A collection of methods used when aggregating data with pandas
[Python] Join two tables with pandas
Extract specific multiple columns with pandas