首页 > 解决方案 > How to check if all columns of a pandas dataframe are equal to a given value

问题描述

I have a dataframe as:

x_data  y_data
2.5      2.5
2.5      2.5
2.5      2.5
2.5      2.5

How do i know that all values of these columns are equal to 2.5

like if I write: if all(df==2.5)

answer should be : 1 1

标签: pandasdataframe

解决方案


import pandas as pd

# test dataframe
df = pd.DataFrame({'x_data': [2.5, 2.5, 2.5, 2.5], 'y_data': [2.5, 2.5, 2.5, 2.5]})

# either implementation can test for equality
df.eq(2.5).all(axis=0)

(df == 2.5).all(axis=0)

# result of either approach
x_data    True
y_data    True
dtype: bool

推荐阅读