0

If I have a DataFrame df:

import pandas as pd

d = {'col1': ['Google','Yahoo','LinkedIn'], 
     'col2': ['Microsoft', 'Oracle', 'Uber']}
df = pd.DataFrame(data=d)

How can I concatenate these columns values into single cells joined with "&", like:

       col1                          col2
0     'Google'&'Yahoo'&'LinkedIn'   'Microsoft'&'Oracle'&'Uber'

Thanks.

S3DEV
  • 8,768
  • 3
  • 31
  • 42
KDWB
  • 73
  • 6
  • 1
    Does this answer your question? [Combine two columns of text in dataframe in pandas/python](https://stackoverflow.com/questions/19377969/combine-two-columns-of-text-in-dataframe-in-pandas-python) – Prachiti Prakash Prabhu Feb 14 '20 at 20:50
  • @PrachitiPrakashPrabhu Thanks for reminding me, but that does not answer my question. I clarify my question. – KDWB Feb 14 '20 at 21:04

1 Answers1

0

Is this what you're after?

Just create a list from the Series (column) values and use the str.join() function to concatenate the values. Then, add back into a new DataFrame.

Sample Code:

import pandas as pd

# Initial dataset.
data1 = {'col1': ['Google','Yahoo','LinkedIn'], 
         'col2': ['Microsoft', 'Oracle', 'Uber']}
df = pd.DataFrame(data=data1)

# Derived dataset.
data2 = {'col1': '&'.join(df['col1'].tolist()),
         'col2': '&'.join(df['col2'].tolist())}
df2 = pd.DataFrame(data2, index=[0])

Output:

    col1                    col2
0   Google&Yahoo&LinkedIn   Microsoft&Oracle&Uber
S3DEV
  • 8,768
  • 3
  • 31
  • 42