[英]Python Pandas DataFrame check if string is other string and fill column
I am learning Python and this might be a noob question: 我正在学习Python,这可能是一个菜鸟问题:
import pandas as pd
A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]
I want to check rowwise if the string in A is in check_list. 我想按行检查A中的字符串是否在check_list中。 The result should be
结果应该是
A YESorNO
0 house YES
1 mouse NO
2 car NO
3 tree YES
Use numpy.where
with isin
: 使用
numpy.where
与isin
:
import pandas as pd
import numpy as np
A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]
A['YESorNO'] = np.where(A['A'].isin(check_list),'YES','NO')
print (A)
A YESorNO
0 house YES
1 mouse NO
2 car NO
3 tree YES
If for some reason you don't want to import numpy, 如果由于某种原因您不想导入numpy,
import pandas as pd
A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]
Here's the one liner: 这是一个班轮:
A['YESorNO'] = ['YES' if x in check_list else 'NO' for x in A['A']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.