[英]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 loc
或
loc
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.