python – How to concatenate multiple column values into a single column in Pandas dataframe

python – How to concatenate multiple column values into a single column in Pandas dataframe

Another solution using DataFrame.apply(), with slightly less typing and more scalable when you want to join more columns:

cols = [foo, bar, new]
df[combined] = df[cols].apply(lambda row: _.join(row.values.astype(str)), axis=1)

you can simply do:

In[17]:df[combined]=df[bar].astype(str)+_+df[foo]+_+df[new]

In[17]:df
Out[18]: 
   bar foo     new    combined
0    1   a   apple   1_a_apple
1    2   b  banana  2_b_banana
2    3   c    pear    3_c_pear

python – How to concatenate multiple column values into a single column in Pandas dataframe

If you have even more columns you want to combine, using the Series method str.cat might be handy:

df[combined] = df[foo].str.cat(df[[bar, new]].astype(str), sep=_)

Basically, you select the first column (if it is not already of type str, you need to append .astype(str)), to which you append the other columns (separated by an optional separator character).

Leave a Reply

Your email address will not be published. Required fields are marked *