简体   繁体   English

Python如何遍历每一行并查看两列之间是否满足条件

[英]Python How to loop through each row and see if condition is met between two columns

I have 3 columns.我有 3 列。 I want to update the third column, status , if the first column, a is greater than or equal to column b + 0.50.我想更新第三列status ,如果第一列a大于或等于列b + 0.50。 I've tried this following code but cannot get it to work:我已经尝试了以下代码,但无法使其正常工作:

if df['a'] >= (df['b'] + 0.50):
    df['status'] = 1

status is already populated with zeros. status已经填充了零。

how would i go about this?我该怎么办?

You can try with np.where您可以尝试使用np.where

df['status'] = np.where(df['a'] >= (df['b'] + 0.50),1,0)

Or just要不就

df['status'] = (df['a'] >= (df['b'] + 0.50)).astype(int)

Or locloc

df.loc[(df['a'] >= (df['b'] + 0.50)),'status'] = 1

You can use lambda function :您可以使用 lambda 函数:

def myFunc(x): 
    if(x[0]>=x[1]+0.50) :
        return 1
    else: return x[2]

df['status'] = df.apply(lambda x:myFunc(x),axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次在for循环python中满足条件时如何添加到空列表? - how to add to an empty list each time a condition is met in a for loop python? 如何遍历df1列以查看df2中满足条件的频率? - How can I loop through column of df1 to see how often condition is met in df2? 如何为每个循环遍历数据帧中的两列? - How to for each loop through two columns in a dataframe? Python:循环浏览两个列表,如果满足条件则添加到它们中,但是每次循环浏览列表中的每个元素 - Python: Loop through two lists, adding to them if condition is met, but looping through every element of the list everytime 如何迭代直到满足python for循环中的条件 - How to iterate until a condition is met in python for loop 在numpy数组中满足条件时如何提取整个行和列 - How to extract the entire row and columns when condition met in numpy array 遍历多个问题,每个问题都有一个条件 Python - loop through multiple questions each with a condition in Python 查看python中满足哪个条件的好方法 - Good way to see which condition is met in python 在两列之间分别对每一行进行排序 - Sort each row individually between two columns 分别遍历 df 行和两列的总和值,直到其中一列满足条件 - Iterate through df rows and sum values of two columns separately until condition is met on one of those columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM