python - 如何检查列中的所有值是否满足 Data Frame 中的条件?

标签 python pandas

如何检查col1 下的所有值 是否满足> 2 等条件?

import pandas as pd

d = [
    {'col1': 3, 'col2': 'wasteful'},
    {'col1': 0, 'col2': 'hardly'},
    ]

df = pd.DataFrame(d)

我可以去

if all(col1 > 2 for i, col1, col2 in df.itertuples()):
    #do stuff

但是有没有一种可读性更高、速度更快和/或内存占用更少的方式?

最佳答案

我认为您需要先创建 bool 掩码,然后再创建 all用于检查是否所有 True:

print (df['col1'] > 2)
0     True
1    False
Name: col1, dtype: bool

print ((df['col1'] > 2).all())
False

关于python - 如何检查列中的所有值是否满足 Data Frame 中的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882363/

相关文章:

python - 如何处理 Pandas 中的多值线终止符

python Pandas : Style column header

python - 为什么 r2_score 在 train_test_split 和 pipeline cross_val_score 之间有很大不同?

python - 类型错误 : '>' not supported between instances of 'int' and 'str'

python - lxml - 当文件名的值相同时,从循环/迭代 Excel 行中保存 xml 会导致错误

python - 在 SQLAlchemy 中使用字典/数据帧值执行更新

python - 在 TensorFlow 中,如何断言列表的值在某个集合中?

python - 获取one-hot编码的H2OFrame

python - 当列数是动态的时,如何从数据框中过滤数据?

python - Pandas 的 DataFrame 合并意外值