Search code examples
python-3.xpandasdataframeconcatenation

Concatenate Each cell in column A with Column B in Python DataFrame


Need help in concatenating each row of a column with other column of a dataframe

Input: enter image description here

Output

enter image description here


Solution

  • Use itertools.product in list comprehension:

    from  itertools import product
    
    L = [''.join(x) for x in product(df['Col1'], df['Col2'])]
    #alternative
    L = [a + b for a, b in product(df['Col1'], df['Col2'])]
    

    df = pd.DataFrame({'Col3':L})
    print (df)
     Col3
    0  AE
    1  AF
    2  AG
    3  BE
    4  BF
    5  BG
    6  CE
    7  CF
    8  CG
    

    Or cross join solution with helper column a:

    df1 = df.assign(a=1)
    df1 = df1.merge(df1, on='a')
    
    df = (df1['Col1_x'] + df1['Col2_y']).to_frame('Col3')