简体   繁体   English

检查行值是否与列表中的值之一匹配,然后在新列中分配 1/0

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

相关问题 检查 substring 的列以分配具有值的新列 - Check a column for substring to assign new columns with values 如何将列表中的随机值分配给同一行的另一列中不存在的新列? - How to assign random values from list to new column that doesn't exist in another column of the same row? 如何将列表中的值分配给 dataframe 中的列/行? - How to assign the values in a list to a column/row in a dataframe? 如何使用python识别几个匹配的列值以选择行并将值从anothe表分配给新列 - How to identify several matching column values to select row and assign value from anothe table to new column with python 匹配列值并将行复制到新的 df - Match column values and copy row to new df 有没有办法根据现有列的当前和前一行值在每行的新列中分配增量值的数量? - Is there a way to assign number of incremental value in a new column of each rows based current and previous row values of existing columns? Pyspark:将一列中的值与另一列中同一行中的列表匹配 - Pyspark: Match values in one column against a list in same row in another column Pandas:如何删除列值与特定值匹配的行(所有值都是值列表) - Pandas : How to drop a row where column values match with a specific value (all value are list of value) 如果此列中的值匹配,Python将在另一列中分配相同的值 - Python assign same value in another column if the values in this column match 检查一个数据框值是否与另一个数据框列匹配,然后在数据框列中设置值 - check if one dataframe values match another dataframe column then set value in dataframe column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM