简体   繁体   中英

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?

这是将列转换为字符串的问题,请使用Series.astype

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM