Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7190837
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T19:36:03+00:00 2026-05-28T19:36:03+00:00

I’m tring to reduce the size of a 2D array by taking the majority

  • 0

I’m tring to reduce the size of a 2D array by taking the majority of square chunks of the array and writing these to another array. The size of the square chunks is variable, let’s say n values on a side. The data type of the array will be an integer. I’m currently using a loop in python to assign each chunk to a temporary array and then pulling the unique values from the tmpArray. I then loop through these and find the one with the most occurances. As you can imagine this process quickly becomes too slow as the input array size increases.

I’ve seen examples taking the min, max, and mean from my square chunks but I don’t know how to convert them to a majority.
Grouping 2D numpy array in average
and
resize with averaging or rebin a numpy 2d array

I’m looking for some means of speeding up this process by using the numpy to perform this process on the entire array. (switching to tiled sections of the array as the input gets too large to fit in memory, I can handle this aspect)

Thanks

#snippet of my code
#pull a tmpArray representing one square chunk of my input array
kernel = sourceDs.GetRasterBand(1).ReadAsArray(int(sourceRow), 
                                    int(sourceCol), 
                                    int(numSourcePerTarget),
                                    int(numSourcePerTarget))
#get a list of the unique values
uniques = np.unique(kernel)
curMajority = -3.40282346639e+038
for val in uniques:
    numOccurances = (array(kernel)==val).sum()
    if numOccurances > curMajority:
        ans = val
        curMajority = numOccurances

#write out our answer
outBand.WriteArray(curMajority, row, col)

#This is insanity!!!

Following the excelent suggestions of Bago I think I’m well on the way to a solution.
Here’s what I have so far. One change I made was to use a (xy, nn) array from the original grid shape. The problem I’m running into is that I can’t seem to figure out how to translate the where, counts, and uniq_a steps from a one dimension to two.

#test data
grid = np.array([[ 37,  1,  4,  4, 6,  6,  7,  7],
                 [ 1,  37,  4,  5, 6,  7,  7,  8],
                 [ 9,  9, 11, 11, 13,  13,  15,  15],
                 [9, 10, 11, 12, 13,  14,  15,  16],
                 [ 17, 17,  19,  19, 21,  11,  23,  23],
                 [ 17, 18,  19,  20, 11,  22,  23,  24],
                 [ 25, 25, 27, 27, 29,  29,  31,  32],
                 [25, 26, 27, 28, 29,  30,  31,  32]])
print grid

n = 4
X, Y = grid.shape
x = X // n
y = Y // n
grid = grid.reshape( (x, n, y, n) )
grid = grid.transpose( [0, 2, 1, 3] )
grid = grid.reshape( (x*y, n*n) )
grid = np.sort(grid)
diff = np.empty((grid.shape[0], grid.shape[1]+1), bool)
diff[:, 0] = True
diff[:, -1] = True
diff[:, 1:-1] = grid[:, 1:] != grid[:, :-1]
where = np.where(diff)

#This is where if falls apart for me as 
#where returns two arrays:
# row indices [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3]
# col indices [ 0  2  5  6  9 10 13 14 16  0  3  7  8 11 12 15 16  0  3  4  7  8 11 12 15
# 16  0  2  3  4  7  8 11 12 14 16]
#I'm not sure how to get a 
counts = where[:, 1:] - where[:, -1]
argmax = counts[:].argmax()
uniq_a = grid[diff[1:]]
print uniq_a[argmax]
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T19:36:04+00:00Added an answer on May 28, 2026 at 7:36 pm

    Here is a function that will find the majority much more quickly, it’s based on the implementation of numpy.unique.

    def get_majority(a):
        a = a.ravel()
        a = np.sort(a)
        diff = np.empty(len(a)+1, 'bool')
        diff[0] = True
        diff[-1] = True
        diff[1:-1] = a[1:] != a[:-1]
        where = np.where(diff)[0]
        counts = where[1:] - where[:-1]
        argmax = counts.argmax()
        uniq_a = a[diff[1:]]
        return uniq_a[argmax]
    

    Let me know if that helps.

    Update

    You can do the following to get your array to be (n*n, x, y), that should set you up to operate on the first axis and get this done in a vectorized way.

    X, Y = a.shape
    x = X // n
    y = Y // n
    a = a.reshape( (x, n, y, n) )
    a = a.transpose( [1, 3, 0, 2] )
    a = a.reshape( (n*n, x, y) )
    

    Just a few things to keep in mind. Even though reshape and transpose return views whenever possible, I believe reshape-transpose-reshape will be forced to copy. Also generalizing the above method to operate on an axis should be possible but might take a little creativity.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am writing an app with both english and french support. The app requests
I have a reasonable size flat file database of text documents mostly saved in
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.