[英]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.