Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshaping pandas DataFrame from Meshgrid

If I construct a pandas DataFrame as follows:

import numpy as np
import pandas as pd

x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx**2+yy**2)
df = pd.DataFrame(z, index=x, columns=y)

I now have a 41x41 DataFrame, where each value corresponds to an x,y pair. I would like to reshape this DataFrame such that I have 3 columns (X,Y,Z) and 1681 rows with a new arbitrary index that ranges from 0-1680.

As a side note, I believe this would be the same as undoing a df.pivot('X','Y','Z') if my dataframe was already in the desired form, but I am unsure of how to accomplish this as well.

like image 565
Brian Pollack Avatar asked May 26 '15 23:05

Brian Pollack


1 Answers

Why not do it all in numpy?

>>> data = np.array([xx, yy, z]).reshape(3, -1).T
>>> data
array([[-5.01      , -5.01      , -0.0652361 ],
       [-4.76      , -5.01      , -0.59221922],
       [-4.51      , -5.01      ,  0.9936343 ], ...
like image 169
Eric Avatar answered Sep 29 '22 10:09

Eric