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.
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 ], ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With