Skip to content
Advertisement

Convert x same size 2D numpy arrays to a 2+x column data frame

I have two ndarrays of size (m x n), and two lists of length m and n respectively. I want to convert the two matrices to a dataframe with four columns. The first two columns correspond to the m and n dimensions, and contain the values from the lists. The next two columns should contain the values from the two matrices. In total, the resulting dataframe should have m times n rows.

Example: If these are the two matrices and two lists,

JavaScript

then the resulting dataframe should look like this:

JavaScript

The order of the rows does not matter.

Although I only have two matrices in this specific case, I am curious about a solution which is easily applicable to any number of same size matrices.

Advertisement

Answer

Use np.vstack for join arrays created by numpy.tile, numpy.repeat and numpy.ravel and pass to DataFrame cosntructor:

JavaScript

For multiple arrays:

JavaScript

Pandas only solution with concat and DataFrame.unstack:

JavaScript

For multiple arrays:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement