Search code examples
pythonpandasnumpycartesian-productcross-product

Applying a function to every element of one column with every element of other column


How can the 2 columns A & B be concatenated using a custom function such that every element of column A is concatenated with every element of column B. Avoiding loops.

A  B
a  1 
b  2
c  3
d  4

Output:

[a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4]


Solution

  • First import product from itertools

    from itertools import product
    
    res = pd.DataFrame((product(df['A'],df['B'])),columns=['A',"B"])
    

    res would be now this
    every value is repeated for each column

        A  B
    0   a  1
    1   a  2
    2   a  3
    3   a  4
    4   b  1
    5   b  2
    6   b  3
    7   b  4
    8   c  1
    9   c  2
    10  c  3
    11  c  4
    12  d  1
    

    Now you can do any custom function you want to apply, As concatenation is mentioned so this is the way

    finalList = list(res['A'].astype(str)+res['B'].astype(str))
    print(finalList)
    
    

    result:

    ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3', 'd4']