Pandas:如果列表中的值存在于行中的任何位置,则标记列
Pandas: Flag column if value in list exists anywhere in row
最终,我想用 0 或 1 标记一个新列 'ExclusionFlag',具体取决于列表中找到的值是否存在于行中的任何位置。
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。
当我在 lambda 表达式中为 'cat' 添加 excluded_codes 列表时,出现错误。
我发现了几个这样的问题,但我通常看到的是类似(见下文)的内容,它调用了特定的列,但我认为遍历 120 列不是最好的方法.虽然我可能是错的。
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
如果你想在新列中使用 True 或 False 值,你可以在没有 Any 和 Astype 的情况下检查它们。
df['ExclusionFlag'] = df.isin(excluded_codes)
您还可以检查特定列:
df['ExclusionFlag'] = df['Code2'].isin(excluded_codes)
最终,我想用 0 或 1 标记一个新列 'ExclusionFlag',具体取决于列表中找到的值是否存在于行中的任何位置。
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。
当我在 lambda 表达式中为 'cat' 添加 excluded_codes 列表时,出现错误。
我发现了几个这样的问题,但我通常看到的是类似(见下文)的内容,它调用了特定的列,但我认为遍历 120 列不是最好的方法.虽然我可能是错的。
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
如果你想在新列中使用 True 或 False 值,你可以在没有 Any 和 Astype 的情况下检查它们。
df['ExclusionFlag'] = df.isin(excluded_codes)
您还可以检查特定列:
df['ExclusionFlag'] = df['Code2'].isin(excluded_codes)