Giuseppe Bonavita
Giuseppe Bonavita

Reputation: 349

Pandas conditional concatenate of a dataframe column

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?

Upvotes: 0

Views: 110

Answers (1)

jezrael
jezrael

Reputation: 862511

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

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

Upvotes: 2

Related Questions