Skip to content

Instantly share code, notes, and snippets.

@megpay
Created July 9, 2022 10:58
Show Gist options
  • Save megpay/1cdf800adf26ba2c815e565300c4af18 to your computer and use it in GitHub Desktop.
Save megpay/1cdf800adf26ba2c815e565300c4af18 to your computer and use it in GitHub Desktop.
Useful numpy functionality
import numpy as np
## Make a table of counts of each value in a numpy array.
# This returns the unique values and their counts in a numpy array.
x = np.array([1, 1, 1, 2, 2, 2, 7, 14, 2, 1])
unique, counts = np.unique(x, return_counts=True)
print(np.asarray((unique, counts)).T) # Use transpose for better visual
## Sort it
# Print out sorted array, first change to dictionary
dict_counts = dict(zip(unique, counts))
print(f"value, count")
print(np.asarray(sorted(dict_counts.items(), key=lambda x:x[1])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment