Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame to multidimensional NumPy Array

I have a Dataframe which I want to transform into a multidimensional array using one of the columns as the 3rd dimension.
As an example:

df = pd.DataFrame({
'id': [1, 2, 2, 3, 3, 3],
'date': np.random.randint(1, 6, 6),
'value1': [11, 12, 13, 14, 15, 16],
'value2': [21, 22, 23, 24, 25, 26]
 })

enter image description here

I would like to transform it into a 3D array with dimensions (id, date, values) like this:
enter image description here
The problem is that the 'id's do not have the same number of occurrences so I cannot use np.reshape().

For this simplified example, I was able to use:

ra = np.full((3, 3, 3), np.nan)

for i, value in enumerate(df['id'].unique()):
    rows = df.loc[df['id'] == value].shape[0]
    ra[i, :rows, :] = df.loc[df['id'] == value, 'date':'value2']

To produce the needed result:
enter image description here
but the original DataFrame contains millions of rows.

Is there a vectorized way to accomplice the same result?

like image 315
Yannis Avatar asked Oct 08 '18 09:10

Yannis


People also ask

How do I convert a DataFrame to a NumPy array?

To convert Pandas DataFrame to Numpy Array, use the function DataFrame. to_numpy() . to_numpy() is applied on this DataFrame and the method returns object of type Numpy ndarray. Usually the returned ndarray is 2-dimensional.

How do you convert a DataFrame to a one dimensional array?

ndarray has the same dimensions as your original DataFrame . Then, run . flatten() to collapse it into one dimension.

Can NumPy arrays be multidimensional?

In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.

How do you convert a DataFrame to a matrix in Python?

A two-dimensional rectangular array to store data in rows and columns is called python matrix. Matrix is a Numpy array to store data in rows and columns. Using dataframe. to_numpy() method we can convert dataframe to Numpy Matrix.


Video Answer


1 Answers

Approach #1

Here's one vectorized approach after sorting id col with df.sort_values('id', inplace=True) as suggested by @Yannis in comments -

count_id = df.id.value_counts().sort_index().values
mask = count_id[:,None] > np.arange(count_id.max())
vals = df.loc[:, 'date':'value2'].values
out_shp = mask.shape + (vals.shape[1],)
out = np.full(out_shp, np.nan)
out[mask] = vals

Approach #2

Another with factorize that doesn't require any pre-sorting -

x = df.id.factorize()[0]   
y = df.groupby(x).cumcount().values
vals = df.loc[:, 'date':'value2'].values
out_shp = (x.max()+1, y.max()+1, vals.shape[1])
out = np.full(out_shp, np.nan)
out[x,y] = vals
like image 174
Divakar Avatar answered Sep 20 '22 16:09

Divakar