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.
So if cell in A
contains "BULL"
, write "Long"
to B
. Or if cell in A
contains "BEAR"
, write "Short"
to B
.
Desired output:
A B "BULL APPLE X5" "Long" "BEAR APPLE X5" "Short" "BULL APPLE X5" "Long"
B is initially empty: df = pd.DataFrame([['BULL APPLE X5',''],['BEAR APPLE X5',''],['BULL APPLE X5','']],columns=['A','B'])
Pandas DataFrame: transpose() function The transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. If True, the underlying data is copied. Otherwise (default), no copy is made if possible.
In the Pandas DataFrame we can find the specified row value with the using function iloc(). In this function we pass the row number as parameter.
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
For your edit:
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)
Or using contains:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With