MaazKhan47
MaazKhan47

Reputation: 849

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]

Upvotes: 0

Views: 95

Answers (4)

Shijith
Shijith

Reputation: 4872

Please have look at the docs of itertools.product to get an understanding of the implementation.

edited the same as below for your need

def product(*args):
    pools = [tuple(pool) for pool in args]
    result = [[]]
    prods = []
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        prods.append(''.join(prod))
    return prods  


product(df['A'], df['B'].astype(str))

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

Upvotes: 1

Andy L.
Andy L.

Reputation: 25239

Another way is using MultiIndex.from_product to create of tuple cartesian products and map to flatten and join them

pd.MultiIndex.from_product([df.A, df.B]).map('{0[0]}{0[1]}'.format).tolist()

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

Upvotes: 0

tawab_shakeel
tawab_shakeel

Reputation: 3739

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']

Upvotes: 1

Who am I
Who am I

Reputation: 67

You can do like this:

a=['a','b','c','d','e']
b=['1','2','3','4','5']
c=[]
for i in range(0,len(a)):
   c.append(a[i]+b[i])

print(c)

Upvotes: -1

Related Questions