gpt4 book ai didi

python - Pandas :如果 A 列中的行包含 "x",则将 "y"写入 B 列中的行

转载 作者:行者123 更新时间:2023-12-03 12:39:54 24 4
gpt4 key购买 nike

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

因此,如果 A 中的单元格包含 "BULL" , 写 "Long"B .或者如果单元格在 A包含 "BEAR" , 写 "Short"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然后添加 B基于 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

或者在创建数据框之前对数据进行逻辑处理:
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

或者只是在后面添加列:
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

关于python - Pandas :如果 A 列中的行包含 "x",则将 "y"写入 B 列中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30953299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com