[英]python For loop to assign value to variable based on value of another var
Yes, Hello coders是的,你好编码员
I'm tring to assign value to the variable within the data frame based on another variable my data looks like:我正在尝试根据我的数据看起来像的另一个变量为数据框中的变量赋值:
Housing_ID Member_ID My_new_staus
1 1
1 2
1 3
1 4
1 5
2 1
2 2
3 1
3 2
3 3
what i want to assign is where the housing id equals to 1 (which is repeated) put the My_new_staus: "Valid"我要分配的是住房 id 等于 1 的位置(重复)放置 My_new_staus:“有效”
I tried to apply it through this code:我试图通过这段代码应用它:
for i in range (len(df['Housing_ID'])):
if df['Housing_ID'][i] == 1 :
df['My_new_staus'][i] = 'Valid'
else:
df['My_new_staus'][i] = ''
and got this message: # Similar to Index.get_value, but we do not fall back to positional KeyError: 398并收到此消息:# 类似于 Index.get_value,但我们不会退回到位置 KeyError: 398
the output that i want is我想要的 output 是
Housing_ID Member_ID My_new_staus
1 1 Valid
1 2 Valid
1 3 Valid
1 4 Valid
1 5 Valid
2 1
2 2
3 1
3 2
3 3
You can use np.where
to assign values to 'My_new_status'
:您可以使用
np.where
将值分配给'My_new_status'
:
df['My_new_status'] = np.where(df['Housing_ID']==1,'valid','')
Output: Output:
Housing_ID Member_ID My_new_status
0 1 1 valid
1 1 2 valid
2 1 3 valid
3 1 4 valid
4 1 5 valid
5 2 1
6 2 2
7 3 1
8 3 2
9 3 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.