Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 2D mesh from two 1D arrays and convert it into a dataframe?

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
like image 338
Haruto.S Avatar asked Sep 03 '20 06:09

Haruto.S


2 Answers

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
like image 94
My Work Avatar answered Nov 15 '22 07:11

My Work


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
like image 35
Henry Yik Avatar answered Nov 15 '22 05:11

Henry Yik