Articles → Pandas → Conditional selection of elements in Dataframe in pandas

Conditional selection of elements in Dataframe in pandas






Example




import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(5,4),['A', 'B', 'C', 'D', 'E'],['W', 'X', 'Y', 'Z'])

print(df)

# conditional selection
print(df[df > 0])











Click to Enlarge



import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(5,4),['A', 'B', 'C', 'D', 'E'],['W', 'X', 'Y', 'Z'])

print(df)


# Conditional selection on columns
print(df[df['W'] > 0])





Click to Enlarge


Applying multiple conditions




import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(5,4),['A', 'B', 'C', 'D', 'E'],['W', 'X', 'Y', 'Z'])

print(df)


# Applying multiple conditions
print((df[(df['W'] > 0) & (df['Y'] > 0)]))





Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, April 18, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250