在panda数据帧中连接两个系列的更快方法



我必须在pandas数据帧中字符串类型的系列列,并希望将其中两个用","分隔的列连接起来,以获得类似"A1,B1"的结果。如何在不使用for循环的情况下快速完成此操作?

确保列A和B都是字符串类型,然后使用

df.A + "," + df.B

语法:Series.str.cat(others=无,sep=无,na_rep=无(

new = data["B1"].copy()
data["A1"]= data["A1"].str.cat(new, sep =", ") 

来源:https://www.geeksforgeeks.org/python-pandas-series-str-cat-to-concatenate-string/

或使用数据帧

df["A1"]=df["A1"]+","+df["B1"]

最新更新