[英]Check if row value match one of values in a list, then assign 1/0 in a new column
How can I create a new column in a pandas dataframe by following these conditions?如何通过遵循这些条件在 pandas dataframe 中创建新列?
if column ' Ex
' match with one of the elements in this list l=['cnn', 'nba', 'agi', 'apple']
then:如果列“
Ex
”与此列表中的元素之一匹配l=['cnn', 'nba', 'agi', 'apple']
则:
Create a new column, S
, having value 1
for those elements in the list above.为上面列表中的那些元素创建一个新列
S
,其值为1
。
For example:例如:
Original dataframe:原厂dataframe:
Ex
cnn
dog
mine
agi
Output expected: Output 预期:
Ex S
cnn 1
dog 0
mine 0
agi 1
I would approach the problem as follows:我将按如下方式处理问题:
df['S']=df['Ex'].apply(lambda x: any([k in x for k in l]))
to check if a row matches (I do not want a 'contains' condition) one of the value within l
.检查行是否与
l
中的一个值匹配(我不想要“包含”条件)。 I do not know how to assign values 1 or 0, but I think adding an if statement.我不知道如何分配值 1 或 0,但我认为添加一个 if 语句。
You can just do isin
你可以做
isin
df['S']=df['Ex'].isin(l).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.