The Python Oracle

combining groups of columns with boolean values to create multiple new columns

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation

--

Chapters
00:00 Combining Groups Of Columns With Boolean Values To Create Multiple New Columns
00:46 Accepted Answer Score 3
01:10 Thank you

--

Full question
https://stackoverflow.com/questions/6357...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #numpy #dataframe #listcomprehension

#avk47



ACCEPTED ANSWER

Score 3


Use itertools.product to get the cartesian product of column names then use Series.mul inside a list comprehension to create corresponding column products, finally use pd.concat to concat these products with df:

from itertools import product

l1, l2 = ['A', 'B'], ['X', 'Y']

c = [df[a].mul(df[b]).rename(''.join([a, b])) for a, b in product(l1, l2)]
df = pd.concat([df] + c, axis=1)

Result:

      A      B     X      Y    AX     AY     BX     BY
0  True  False  True  False  True  False  False  False