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])
- I have created a dataframe in pandas.
- 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.
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