Baron
Baron

Reputation: 55

Numpy reshape "reversal"

I read a 4D array from a file which is given in a 2D form i, j, k, x, y, z. Input file header and shape I use numpy.reshape to reshape the 2D array to it's 3-D form. After making changes to this, I wish to write the file exactly the same order / format as I read it. I do not understand how to "reverse" numpy.reshape to put it back in the same format.

import numpy as np    
import pandas as pd
from pandas import read_csv 


header = read_csv("Input/Grid1_test.csv", nrows=1,skipinitialspace=True)

print header.head()

imax=header['IMAX'].iloc[0]
jmax=header['JMAX'].iloc[0]
kmax=header['KMAX '].iloc[0]

print(imax,jmax,kmax)

#read grid data with numpy array .. it is slow but probably worth it 
grid_data = np.loadtxt('Input/Grid1_test.csv', delimiter=',', skiprows=3)


size_arr = np.array(grid_data).reshape(kmax, jmax, imax, 6)

#do something

#write the grid back into the file

Upvotes: 5

Views: 10577

Answers (1)

Henry Woody
Henry Woody

Reputation: 15692

To "reverse" a reshape, you can just call reshape again on the array to reshape it into the original dimensions.

If you have an array x with dimensions (n, m) then:

x.reshape(kmax, jmax, imax, 6).reshape(n, m) == x

Upvotes: 7

Related Questions