[英]How to check whether all values in a column satisfy a condition in Data Frame?
How can I check if all values under col1
satisfy a condition such as > 2
?如何检查col1
下的所有值是否满足> 2
之类的条件?
import pandas as pd
d = [
{'col1': 3, 'col2': 'wasteful'},
{'col1': 0, 'col2': 'hardly'},
]
df = pd.DataFrame(d)
I could go我可以 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?但是否有更易读、更快和/或占用空间更少的 memory 方式?
You can also use numpy.where to check if all column of a dataframe satisfies a condition 您还可以使用numpy.where检查数据帧的所有列是否满足条件
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
A further option is the application of lambda-Functions另一种选择是应用 lambda 函数
import pandas as pd
df = pd.DataFrame(
[{'col1': 3, 'col2': 'wasteful'},
{'col1': 0, 'col2': 'hardly'},
{'col1': 9, 'col2': 'stuff'}])
print(df['col1'].apply(lambda x: True if ((x>2) & (x<8)) else False))
#result:
#0 True
#1 False
#2 False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.