Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple/efficient way to expand a pandas dataframe

Tags:

python

pandas

Say i have a list and a pandas dataframe

import pandas as pd
x = pd.DataFrame({'a': range(2), 'b': range(2)})
y = [1,2,3]

I want to get a dataframe that looks roughly like this:

a  b  y
0  0  1
1  1  1
0  0  2
1  1  2
0  0  3
1  1  3

Is there a simple way to do this?

like image 351
qua Avatar asked Dec 25 '22 16:12

qua


1 Answers

That is called cartesian product. Convert to dataframe

>>> y = pd.DataFrame(y, columns=list('y'))

add constant key

>>> x['k'] = 1
>>> y['k'] = 1

and merge over it

>>> pd.merge(y, x, on='k')[['a', 'b', 'y']]
   a  b  y
0  0  0  1
1  1  1  1
2  0  0  2
3  1  1  2
4  0  0  3
5  1  1  3
like image 70
alko Avatar answered Jan 06 '23 10:01

alko