Home > Mobile >  Convert Dataframe into (first panel of) 3D array
Convert Dataframe into (first panel of) 3D array

Time:12-31

I have the following Dataframe named df1:

A B
0 5 10
1 15 20
2 25 30

Now, let's say I also have the following blank 3D array (created just as placeholder for now):

array1 = np.zeros((10,3,2))

With df1 having the same number of rows and columns, how can I replace the 1st "panel" (of ten "panels") in array1 with df1?

CodePudding user response:

Try this:

array1[0] = df1

Output:

>>> array1
array([[[ 5., 10.],
        [15., 20.],
        [25., 30.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

        ...

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]]])

CodePudding user response:

You can directly assign the DataFrame to the first "panel":

array1[0] = df

print(array1)
# Output:
[[[ 5. 10.]
  [15. 20.]
  [25. 30.]]

 [[ 0.  0.]
  [ 0.  0.]
  [ 0.  0.]]

 [[ 0.  0.]
  [ 0.  0.]
  [ 0.  0.]]
# ...followed by 7 more identical 3x2 zero matrices

Out of habit, I first tried array1[0, :, :] = df.to_numpy(), which gives the same result, as far as I can tell, but is more explicit in its intent.

CodePudding user response:

you can directly assign like richardec mentioned

array1[0] = df1

you can also try this to know what is happening internally

array=np.array(df)
array1[0]=array

output is same in both the cases

array([[[ 5., 10.],
        [15., 20.],
        [25., 30.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]]])
  • Related