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])




  1. I have created a dataframe in pandas.
  2. Apply the conditional selection using df[df > 0] to check the elements greater than zero. This condition will return an array. The values in the array follows this rule - If the value is greater than zero, then returns the number else NaN.


Picture showing the dataframe that returns the elements having value greater than zero

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])




Picture showing the conditional selection on columns of the dataframe in pandas

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)]))




Picture showing the multiple conditions applied on the dataframe in pandas

Click to Enlarge


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250