Python >> Tutoriel Python >  >> Python Tag >> Array

Comment générer un maillage 2D à partir de deux tableaux 1D et le convertir en dataframe ?

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])})

donne :

   x   y
0  1  10
1  1  11
2  2  10
3  2  11
4  3  10
5  3  11

Vous pouvez utiliser 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

Ou pour une raison quelconque, vous souhaitez appeler la méthode directement :

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

import numpy as np
x = np.array([1,2,3])
y = np.array([10, 11])

yv, xv = np.meshgrid(y, x)
df = pd.DataFrame(dict(x=xv.ravel(), y=yv.ravel()))

sortie :

   x   y
0  1  10
1  1  11
2  2  10
3  2  11
4  3  10
5  3  11