Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert a vector into inverse frequencies

So given this numpy array:

import numpy as np

vector = np.array([1, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 1])  

# len(vector) == 12
# 2 x ones, 4 x two, 6 x three

How can I convert this into a vector of inverse frequencies?

Such that for each value, the output contains 1 divided by the frequency of that value:

array([0.16, 0.33, 0.33, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.33, 0.33, 0.16])
like image 718
James Schinner Avatar asked Jul 13 '26 09:07

James Schinner


1 Answers

[Update to a general one]

How about this one using np.histogram:

import numpy as np

l = np.array([1,2,2,3,3,3,3,3,3,2,2,1])
_u, _l = np.unique(l, return_inverse=True)
np.histogram(_l, bins=np.arange(_u.size+1))[0][_l] / _l.size
like image 83
ChoF Avatar answered Jul 14 '26 23:07

ChoF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!