The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
00:58 Accepted answer (Score 3)
01:31 Thank you

--

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

Accepted answer links:
[itertools.product]: https://docs.python.org/3/library/iterto...
[Series.mul]: https://pandas.pydata.org/pandas-docs/st...
[pd.concat]: https://pandas.pydata.org/pandas-docs/st...

--

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