I have to string type series columns in a pandas data frame and want to concatenate the two of them separated by a ", " to get a result like 'A1, B1'. How can I do this in a quick way without using a for loop?
2 Answers
make sure column A and B are both string type and then use
df.A + "," + df.B
1 Comment
Aryerez
Or even better. don't pre-"make sure" and do:
df.A.astype(str) + "," + df.B.astype(str)Syntax: Series.str.cat(others=None, sep=None, na_rep=None)
new = data["B1"].copy()
data["A1"]= data["A1"].str.cat(new, sep =", ")
source:https://www.geeksforgeeks.org/python-pandas-series-str-cat-to-concatenate-string/
or using dataframe
df["A1"]=df["A1"]+","+df["B1"]