For example, I have two arrays:
import numpy as np
x = np.array([1,2,3])
y = np.array([10, 11])
How can I generate a pandas dataframe with every combination of x and y, like below?
x y
1 10
1 11
2 10
2 11
3 10
3 11
import pandas as pd
import numpy as np
x = np.array([1,2,3])
y = np.array([10, 11])
pd.DataFrame({'x':np.repeat(x,y.shape[0]),
'y':np.tile(y,x.shape[0])})
yields:
x y
0 1 10
1 1 11
2 2 10
3 2 11
4 3 10
5 3 11
You could use pd.Multiindex.from_product
:
pd.DataFrame(index=pd.MultiIndex.from_product([x, y])).reset_index()
level_0 level_1
0 1 10
1 1 11
2 2 10
3 2 11
4 3 10
5 3 11
Or for some reason you want to call the method directly:
from pandas.core.reshape.util import cartesian_product
print (pd.DataFrame(cartesian_product([x, y])).T)
0 1
0 1 10
1 1 11
2 2 10
3 2 11
4 3 10
5 3 11
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