1

I have 2 pandas series that look like this:

import pandas as pd
listA = [5,4,3]
listB = ["a","b","c"]
s = pd.Series(listA)
print(s)
p = pd.Series(listB)
print(p)

And I would like to obtain a list of the 2 lists mixed together as strings like this:

listTogether = ["a5","a4","a3","b5","b4","b3","c5","c4","c3"]
t = pd.Series(listTogether)
print(t)

Do you have any hint? Is it possible to do by avoiding loops?

Thanks so much in advance for the help

1
  • What have you tried? This could be achieved with zip and a comprehension/map. Commented Nov 28, 2018 at 17:06

4 Answers 4

5

A trick from MultiIndex

listTogether = pd.MultiIndex.from_product([p,s.astype(str)]).map(''.join).tolist()
listTogether 
Out[242]: ['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is exactly what I was looking for. I have always been struggling on how to use MultiIndex. Thanks!
2

You are looping whether you like it or not.

[f'{b}{a}' for b in listB for a in listA]

['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3']

Comments

1

You can use itertools product

from itertools import product

pd.DataFrame(list(product(p.tolist(),s.astype(str).tolist()))).apply(''.join, axis = 1).tolist()

839 µs ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

['a5', 'a4', 'a3', 'b5', 'b4', 'b3', 'c5', 'c4', 'c3']

If you want a very efficient solution, go pure python way

[''.join(i) for i in list(product(p.tolist(),s.astype(str).tolist()))]
79 µs ± 924 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Comments

0

The use of zip may help you.

You can do something like that for your lists, however it involves a for loop :

listTogether = ['{}{}'.format(a,b) for (a,b) in zip(listA,listB)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.