Issue
Hello given a dataframe I would like to check that all the values of a particular column are equal to 9.
import pandas as pd
import numpy as np
df = pd.DataFrame(data=[[1,2],[2,9],[np.nan,9],[3,9]],columns=['A','B'])
df
A B
0 1.0 2
1 2.0 9
2 NaN 9
3 3.0 9
My solution would be:
if ((df.loc[:,"B"].unique()==[9]).all()):
...
Is there a better way to do so?
Solution
Use DataFrame.all
with compare by Series.eq
:
if df.B.eq(9).all():
print ('all values are 9')
EDIT: Like mentioned @mozway use:
assert df.B.eq(9).all()
#AssertionError
With custom error:
if df.B.ne(9).any():
raise Exception('All values in column are not equal 9')
Exception: All values in column are not equal 9
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.