How can I check if all values under col1
satisfy a condition such as > 2
?
import pandas as pd
d = [
{'col1': 3, 'col2': 'wasteful'},
{'col1': 0, 'col2': 'hardly'},
]
df = pd.DataFrame(d)
I could go
if all(col1 > 2 for i, col1, col2 in df.itertuples()):
#do stuff
but is there a more readable, faster and/or has less memory footprint way?
all() method checks whether all elements are True, potentially over an axis. It returns True if all elements within a series or along a Dataframe axis are non-zero, not-empty or not-False.
You can check if a column contains/exists a particular value (string/int), list of multiple values in pandas DataFrame by using pd. series() , in operator, pandas. series. isin() , str.
Pandas DataFrame all() Method The all() method returns one value for each column, True if ALL values in that column are True, otherwise False. By specifying the column axis ( axis='columns' ), the all() method returns True if ALL values in that axis are True.
I think you need create boolean mask and then all
for check if all True
s:
print (df['col1'] > 2)
0 True
1 False
Name: col1, dtype: bool
print ((df['col1'] > 2).all())
False
You can also use numpy.where to check if all column of a dataframe satisfies a condition
import numpy as np
import pandas as pd
d = [
{'col1': 3, 'col2': 'wasteful'},
{'col1': 0, 'col2': 'hardly'},
]
df = pd.DataFrame(d)
print(all(np.where(df['col1'] > 2, True, False)))
#False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With