简体   繁体   English

熊猫数据框:如果A,B或C列中的行包含“ x”或“ y”,则将“ z”写入新列

[英]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 使用isinanyastype

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.

相关问题 熊猫:如果A列中的行包含字符串“ x”,“ y”,“ z”,请在B列中写“ x _”,“ y _”,“ z_” - Pandas: if row in column A contains strings “x”,“y”,“z”, write “ “x_”,“y_”,“z_” to row in column B Pandas:如果 A 列中的行包含“x”,则将“y”写入 B 列中的行 - Pandas: if row in column A contains "x", write "y" to row in column B 筛选 pandas dataframe 行,其中具有列 A 和值 X 的特定行具有列 B,其值 Y 大于参数 Z - Filter pandas dataframe rows where a specific row with column A and value X has column B with value Y greater than a parameter Z 熊猫:如果A列包含“ x”,则有条件地将子字符串“ y” +“ z”附加到B列 - Pandas: Conditionally append substrings “y”+“z” to column B if column A contains “x” Pandas - 如果列 y 包含 b,则从列中获取值 x - Pandas - Grab value x from column a if column y contains b 如果列字符串包含 X 和 [Y,Z] 中的至少一个,则捕获行 - Capturing row if column string contains X and at least one of [Y,Z] Python Pandas如果B列中的值等于[X,Y,Z],则将A列替换为“ T” - Python Pandas If value in column B = equals [X, Y, Z] replace column A with “T” 如何将 Y 列连接到 X 列并在 pandas dataframe 中复制值 Z? - How to concat column Y to column X and replicate values Z in pandas dataframe? Pandas DataFrame 过滤列 A 取决于列 B 是否包含 A 中一组值的 x - Pandas DataFrame filter column A depending on if column B contains x for group of values in A Python/Pandas - 如果 A 列等于 X 或 Y,则从 Col B 分配值。如果不是,则分配 Col C。 Python怎么写? - Python/Pandas - If Column A equals X or Y, then assign value from Col B. If not, then assign Col C. How to write in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM