Elliot Huebler
Elliot Huebler

Reputation: 137

Python: Counting Points from 2 1D Arrays

I have a data set of 2 1D arrays. My goal is to count the points in each section of a grid (with a size of my choosing).

plt.figure(figsize=(8,7))
np.random.seed(5)
x = np.random.random(100)
y = np.random.random(100)

plt.plot(x,y,'bo')
plt.grid(True)

My Plot

I would like to be able to split each section into is own unique set of 2 1D or 1 2D arrays.

Upvotes: 0

Views: 272

Answers (2)

Brenden Petersen
Brenden Petersen

Reputation: 2022

This function takes in two 1D arrays and returns a 2D matrix, in which each element is the number of points in the grid section corresponding to your image:

import numpy as np

def count_points(arr1, arr2, bin_width):
    x = np.floor(arr1/bin_width).astype(int) # Bin number for each value
    y = np.floor(arr2/bin_width).astype(int) # Bin number for each value
    counts = np.zeros(shape=(max(x)+1, max(y)+1), dtype=int)
    for i in range(x.shape[0]):
        row = max(y) - y[i]
        col = x[i]
        counts[row, col] += 1
    return counts

Note that x and y don't line up with the column and row index, since the origin is at the bottom left in the plot but the "origin" (index [0,0]`) of the matrix is the top left. I rearranged the matrix so that the elements line up with what you see in the photo.

Example:

np.random.seed(0)
x = np.random.random(100)
y = np.random.random(100)
print count_points(x, y, 0.2) # 0.2 matches the default gridlines in matplotlib

# Output:
#[[8 4 5 4 0]
# [2 5 5 7 4]
# [7 1 3 8 3]
# [4 2 5 3 4]
# [4 4 3 1 4]]

Which matches the counts here:

enter image description here

Upvotes: 0

Austin A
Austin A

Reputation: 566

import numpy as np

def split(arr, cond):
  return [arr[cond], arr[~cond]]

a = np.array([1,3,5,7,2,4,6,8])
print split(a, a<5)

this will return a list of two arrays containing [1,2,3,4] and [5,6,7,8].

Try using this function based on the conditions you set (intervals of 0.2 it seems)

NOTE: to implement this correctly for your problem, you'll have to modify the split function seeing that you want to split the data into more than two sections. I'll leave that as an exercise for you to do :)

Upvotes: 1

Related Questions