0

This question is an extension of Pandas conditional creation of a series/dataframe column

Given the below dataframe:

df = pd.DataFrame(np.random.randint(0,20,size=(10, 2)), columns=list('AB'))
df["note"]="old note"

I need to update A and note columns when A>B. This is what I tried:

df.loc[df.A>df.B, "note"]="A was: "+str(df.A)
df.loc[df.A>df.B, "A"]=df.B

and

df["note"]=np.where(df.A>df.B, "A was: "+str(df["A"]), df["note"])
df.loc[df.A>5, "A"]=df.B

the note column does not come out clean, it concatenates the entire A column in a single cell, while I would like to keep only the value of the same row. could you please help?

1 Answer 1

2

Here is problem with casting column to strings, use Series.astype:

df.loc[df.A>df.B, "note"]="A was: "+df.A.astype(str)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.