[英]Pandas Dataframe: if row in column A, B or C contains “x” or “y”, write “z” to new column
Very similar to this question: Pandas: if row in column A contains "x", write "y" to row in column B 与此问题非常相似: 熊猫:如果A列中的行包含“ x”,则将“ y”写入B列中的行
I want to know if a row contains "x" or "y" in multiple different columns then output "z" to a new column. 我想知道一行是否在多个不同的列中包含“ x”或“ y”,然后将“ z”输出到新列。
INPUT: INPUT:
A B C
Cat Dog Pig
Monkey Tiger Cat
Cow Sheep Goat
If "cat" or "tiger" or "lion" - output 1 to new column 如果是“ cat”或“ tiger”或“ lion”-将1输出到新列
OUTPUT OUTPUT
A B C CAT FAMILY
Cat Dog Pig 1
Monkey Tiger Cat 1
Cow Sheep Goat 0
Use isin
with any
and astype
使用
isin
与any
和astype
In [298]: cat_family = ["Cat", "Tiger", "Lion"]
In [303]: df['CAT_FAMILY'] = df.isin(cat_family).any(1).astype(int)
In [304]: df
Out[304]:
A B C CAT_FAMILY
0 Cat Dog Pig 1
1 Monkey Tiger Cat 1
2 Cow Sheep Goat 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.