title: How can I efficiently convert a 4D numpy array into a pandas DataFrame with indices as columns?
body: <p>I have a 4D numpy array of shape (4, 155, 240, 240). I would like to create a pandas DataFrame with one row for each element of this array, and five columns: one for each of the four indices, and one for the value in the array. The code I'm using right now looks like this:</p>
  
  <pre class="lang-python prettyprint-override"><code>import pandas as pd
  import numpy as np
  
  # some array of this shape
  im = np.zeros((4, 155, 240, 240))
  
  df = {col: [] for col in ['mode', 'x', 'y', 'z', 'val']}
  for idx, val in np.ndenumerate(im):
      df['mode'].append(idx[0])
      df['y'].append(idx[1])
      df['x'].append(idx[2])
      df['z'].append(idx[3])
      df['val'].append(val)
  df = pd.DataFrame(df)
  </code></pre>
  
  <p>Is there a way to do this more efficiently, possibly using vectorized operations?</p>