简体   繁体   English

根据多个列中至少有一个是否包含列表中的值这一事实创建新列(Python,熊猫)

[英]creating new column based on the fact whether at least 1 of multiple columns contains value from the list (Python, pandas)

I am trying to create a column which will have True/Falses or 1/0 based on the fact whether at least one of the N columns contains values from the list我正在尝试根据 N 列中是否至少有一个包含列表中的值这一事实创建一个具有 True/Falses 或 1/0 的列

I do it in the following way我通过以下方式进行

list = ['apple', 'banana', 'orange']
df['new'] = df['One'].isin(mylist) | df['Two'].isin(mylist).... |df['N'].isin(mylist) 

Is there a faster way to write condition to evaluate that I have "True" in a new column if at least one the N columns contains a value?如果 N 列中至少有一个包含值,是否有更快的方法来编写条件来评估我在新列中有“真”?

I tried to do我试着做

cols = ['One',...'N']
df['new'] = df[cols].isin(mylist)

But it does not work但它不起作用

You are close, need DataFrame.any for test if at least one True per row:你很接近,需要DataFrame.any来测试每行是否至少有一个True

df['new'] = df[cols].isin(mylist).any(axis=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建新列以指定列是否包含单词 - Creating new columns to assign value whether a column contains a word 基于多列创建新列 pandas - Creating new column based on multiple columns pandas 基于python pandas中其他列的值创建新列 - Creating a new column based on values from other columns in python pandas 根据其他行和列的多个条件在数据框中创建新列? 包括空行? - 蟒蛇/熊猫 - Creating a new column in dataframe based on multiple conditions from other rows and columns? Including rows that are null? - Python/Pandas Pandas: Python 检查多列如果包含值然后将值返回到新列 - Pandas: Python check Multiple columns if contains value then return value to new column Pandas DataFrame中的新列,基于列表中是否有任何值出现在数据集中 - New column in Pandas DataFrame based on whether any value from a list appears in the dataset 使用Pandas,我是否可以创建一个新列,该新列基于值是否跨多个列存在而返回二进制变量? - Using Pandas, can I create a new column that returns a binary variable based on whether a value exists across multiple columns? 跟进 - 根据 Pandas 中另一列的值创建新列 - Follow up - Creating new columns based on value from another column in pandas Pandas dataframe:根据其他列的数据创建新列 - Pandas dataframe: Creating a new column based on data from other columns 如何根据另一列中的值是否包含列表的值来创建新列? - How to create a new column based on whether the value in another column contains values of a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM