pandas :如果列表中的值存在于行中的任何位置,则标记列 [英] Pandas: Flag column if value in list exists anywhere in row

查看:67
本文介绍了 pandas :如果列表中的值存在于行中的任何位置,则标记列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最终,我想用0或1标记一个新列 ExclusionFlag,具体取决于列表中找到的值是否存在于该行的任何位置。

Ultimately, I want to flag a new column, 'ExclusionFlag', with 0 or 1 depending on whether a value that is found in a list exists anywhere in the row.

df = pd.DataFrame([['cat','b','c','c'],['a','b','c','c'],['a','b','c','dog'],['dog','b','c','c']],columns=['Code1','Code2','Code3','Code4'])
excluded_codes = ['cat','dog']

#Attempt
df['ExclusionFlag'] = df.apply(lambda x: 'cat' in x.values, axis=1).any()

#Desired outcome
#Side note: I have 120 rows to check. They're labeled Code1, Code2...Code120. 

    Code1   Code2   Code3   Code4   ExclusionFlag
0   cat     b       c       c       1
1   a       b       c       c       0
2   a       b       c       dog     1
3   dog     b       c       c       1

我拥有的代码行将每一行标记为True。

The line of code I have marks every row as True.

当我在lambda表达式中为 cat添加exclude_codes列表时,出现错误。

And when I add the excluded_codes list in for 'cat' in my lambda expression, I get an error.

我发现了几个类似的问题,但是我通常看到的是类似(见下文)的内容,它指出了特定的列,但是我没有认为迭代120列是最好的方法。虽然我可能是错的。

I found a couple questions like this, but what I see typically is something along the lines of (see below), which calls out a specific column, but I don't think iterating through 120 columns is the best approach. Although I could be wrong.

df['ExclusionFlag'] = df['Code1'].isin(exclusion_codes)


推荐答案

类似

df['ExclusionFlag'] = df.isin(excluded_codes).any(1).astype(int)

    Code1   Code2   Code3   Code4   ExclusionFlag
0   cat     b       c       c       1
1   a       b       c       c       0
2   a       b       c       dog     1
3   dog     b       c       c       1

这篇关于 pandas :如果列表中的值存在于行中的任何位置,则标记列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆