pandas - 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
解决方案
- 内置的python函数,
all()
不允许选择一个索引来比较值。 - 使用
pandas.DataFrame.eq
或Boolean
比较, 确定元素与值的相等性。 - 使用
pandas.DataFrame.all
,这将返回是否所有元素都是True
,可能在一个轴上。
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
推荐阅读
- tensorflow - Keras 中的贪心初始化
- sql-server - SSIS 管理多个包上的连接字符串密码
- ssl - Gitlab SSL握手失败的服务器很可能需要客户端证书
- c# - 查询 LinqToXML
- android - 在 Android Studio 中切换 Activity 时总是报错
- c# - 这些 foreach 循环可以合并为一个吗?
- assembly - 将 AH 存储到 DW 变量中时“操作数类型不匹配”
- nginx - 如何将 auth_request 发送到 nginx 中的变量 URI?
- asp.net - 将 asp.net 核心应用程序发布到 azure 时出错
- php - 如何使用孩子创建 json 数组 php