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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With