'Convert 2D meshgrid into a 3D array in Python

I have coordinates (lat, lon) in a meshgrid, and data asociated with each "point". I want to export into a .csv and have each point asociated with the data i want to analyze. So far, my code looks like this.

xx1,yy1=np.meshgrid(xx,yy)
row_format = np.stack([z.ravel() for z in (xx1, yy1, data['Hs'])], axis=1)
print(row_format)
pd.DataFrame(row_format).to_csv('sample.csv')

The data is in a dataframe that has a certain order. But the output is as follows:

x y Hs
265 19 0
266 19 1
267 19 2

And it should be as follows, in order to make sense with the data order:

x y Hs
265 19 0
265 18 1
265 17 2

I only need to make the "x" column to be the one with the "still" value while the "y" column goes through its values ("x" will change value once every "y" value has been written). Anyone know how to change that order? Or another way to get my desired output?



Solution 1:[1]

Assuming your dataframe is called df, you could do the following. Some notes:

  • y_cycle currently goes from 19 to 1 inclusive (so 19 values total). Change the 0 to -1 in the np.arange statement if you want a total of 20 values before y cycles back to the beginning.
  • The final 2 lines replace the x and y columns in your current df. If you want the new x and y values (stored in repeated_x and repeated_y to be new columns, you can change df["x"] to a different column name, and same for df["y"].
y_cycle = np.arange(19, 0, -1)
length_y_cycle = len(y_cycle)
x_start = 265
length = len(df)

num_y_cycles = int(math.ceil(length / length_y_cycle))
repeated_y = np.tile(y_cycle.reshape(1, length_y_cycle), num_y_cycles)[0][:length]

x_fin = x_start + num_y_cycles - 1
repeated_x = np.repeat(np.arange(x_start, x_fin+1, 1), length_y_cycle)[:length]

df["x"] = repeated_x
df["y"] = repeated_y

Let me know if you have any questions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AJH