pandas :如果列A中的行包含"x",则写"y".在B列中行 [英] Pandas: if row in column A contains "x", write "y" to row in column B

查看:85
本文介绍了 pandas :如果列A中的行包含"x",则写"y".在B列中行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于pandas,我正在寻找一种方法,用于根据A列中相应行的子字符串将条件值写入B列中的每一行.

For pandas, I'm looking for a way to write conditional values to each row in column B, based on substrings for corresponding rows in column A.

因此,如果A中的单元格包含"BULL",则将"Long"写入B.或者,如果A中的单元格包含"BEAR",则将"Short"写入B.

So if cell in A contains "BULL", write "Long" to B. Or if cell in A contains "BEAR", write "Short" to B.

所需的输出:

A                  B
"BULL APPLE X5"    "Long"
"BEAR APPLE X5"    "Short"
"BULL APPLE X5"    "Long"

B最初为空:df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']],columns=['A','B'])

推荐答案

当您错误地创建数据框时,您的代码将出错,只需创建单个列A,然后基于A添加B:

Your code would error as you creating the Dataframe incorrectly, just create a single column A then add B based on A:

import pandas as pd
df = pd.DataFrame(["BULL","BEAR","BULL"], columns=['A'])
df["B"] = ["Long" if ele  == "BULL" else "Short" for ele in df["A"]]

print(df)

    A      B
0  BULL   Long
1  BEAR  Short
2  BULL   Long

还是在创建数据框之前先对数据进行逻辑处理

Or do you logic with the data before you create the dataframe:

import pandas as pd
data = ["BULL","BEAR","BULL"]
data2 = ["Long" if ele  == "BULL" else "Short" for ele in data]
df = pd.DataFrame(list(zip(data, data2)), columns=['A','B'])

print(df)
      A      B
 0  BULL   Long
 1  BEAR  Short
 2  BULL   Long

供您

df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']], columns=['A','B'])

df["B"] = df["A"].map(lambda x: "Long" if "BULL" in x else "Short" if "BEAR" in x else "")

print(df)

            A      B
0  BULL APPLE X5   Long
1  BEAR APPLE X5  Short
2  BULL APPLE X5   Long

或仅在以下位置添加列:

Or just add the column after:

df = pd.DataFrame(['BULL APPLE X5','BEAR APPLE X5','BLL APPLE X5'], columns=['A'])

df["B"] = df["A"].map(lambda x: "Long" if "BULL" in x else "Short" if "BEAR" in x else "")

print(df)

或使用包含:

df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']], columns=['A','B'])


df["B"][df['A'].str.contains("BULL")] = "Long"
df["B"][df['A'].str.contains("BEAR")] = "Short"

print(df)
0  BULL APPLE X5   Long
1  BEAR APPLE X5  Short
2  BULL APPLE X5   Long

这篇关于 pandas :如果列A中的行包含"x",则写"y".在B列中行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆