Created
July 9, 2022 10:58
-
-
Save megpay/1cdf800adf26ba2c815e565300c4af18 to your computer and use it in GitHub Desktop.
Useful numpy functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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