简体   繁体   English

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

[英]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 方式?

I think you need create boolean mask and then all for check if all True s: 我认为你需要创建布尔掩码然后all检查所有True s:

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

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

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.

相关问题 创建一个新列,该列是一行中有多少条目满足pandas中数据帧的每一行条件的计数 - Create new column that is a count of how many entries in a row satisfy a condition for each row of a data frame in pandas 如何根据条件统计所有数据框列值并将列转置为 Python 中的行 - How to count all data frame column values based on condition and transpose the columns into rows in Python 如何检查熊猫数据框中同一列中的所有其他列值? - How to check column value among all others values in same column in Pandas Data frame? 如果它们满足 Pandas 中的条件,如何将列的唯一值存储为列表? - how to store unique values of column as a list if they satisfy a condition in Pandas? 如何为满足特定条件的数据框的行赋值? - How to assign values to the rows of a data frame which satisfy certain conditions? 如何根据条件对多索引数据框中的列值进行计数 - How to count column values in multiindex data frame based on condition Pandas 数据框 - 将前一列中与特定条件匹配的所有值相加并将其添加到新列中 - Pandas Data Frame - Sum all the values in a previous column which match a specific condition and add it to a new column 如何检查数据框列值是否出现在数据框列中的所有唯一年份中 - How to check if data frame column value appears in all unique year in the data frame column 要检查 Pandas Dataframe 列是否为 TRUE/FALSE,如果为 TRUE,请检查另一列是否满足条件并生成具有值 PASS/FAIL 的新列 - To check Pandas Dataframe column for TRUE/FALSE, if TRUE check another column for condition to satisfy and generate new column with values PASS/FAIL Python:迭代数据框列,检查存储在数组中的条件值,并将值获取到列表中 - Python: Iterate over a data frame column, check for a condition-value stored in array, and get the values to a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM