Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I sample every other value in a grid while ensuring it alternates each row to create an offset?

I would like to take a grid of evenly spaced points and sample every other value while ensuring that each row is offset from the one before. I have been able to make this fairly easily when the number of x points in the grid is odd, but not when they are even.

As an Example the original grid looks like:

import pandas as pd
import numpy as np

x = np.array(range(1, 6))
y = np.array(range(1, 6))
df = pd.DataFrame(np.array(np.meshgrid(x, y, )).T.reshape(-1, 2), columns= {'x', 'y'})
df.plot.scatter('x', 'y')

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have used

df_2 = df[::2]
df_2.plot.scatter('x', 'y')

enter image description here

But I cannot figure out how to make it work when the number of x values is even.

For background, I am new to python (coming from R) and I am trying to sample geospatial data at even longitudinal intervals and offset for every change in latitude for even spatial coverage. It is hard to guarantee that each point grid will start with an odd number of x values as they are already random samples of spatial data.

>Solution :

You can add a new map column (true/false) which can be calculated by checking the modulus 2 of the index of the df row.

UPDATED: changed calculation to rely entirely on x and y values to determine inclusion.

import pandas as pd
import numpy as np

x = np.array(range(1, 6))
y = np.array(range(1, 6))
df = pd.DataFrame(np.array(np.meshgrid(x, y, )).T.reshape(-1, 2), columns= {'x', 'y'})    
df['includepoint'] = (df.y  + df.x) % 2 == 0   
df[df.includepoint].plot.scatter('x', 'y')

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading