Question

I have a m*n numpy matrix of float type. I am going to use the Counter function (from collections) to derive count of certain combination of matrix elements. On experimenting, I found that Counter() requires string value entries to iterate whereas my numpy matrix was by default a float type.

Using dtype while declaring the numpy matrix of zeros doesnt help.

So, I thought of converting each element of the numpymatrix into a string. But, its not working. How do i do it?

Was it helpful?

Solution

xx = np.matrix([[1.2,3.4],[5.4,6.7],[9.8, 5.2]])
zz = np.matrix([[str(ele) for ele in a] for a in np.array(xx)])

Result:

>>> xx
matrix([[ 1.2,  3.4],
        [ 5.4,  6.7],
        [ 9.8,  5.2]])
>>> zz
matrix([['1.2', '3.4'],
        ['5.4', '6.7'],
        ['9.8', '5.2']], 
       dtype='|S3')

OTHER TIPS

It is unclear exactly what you are trying to do, but you might be better suited using np.histogram (or possibly np.bincount) to derive counts based on a numpy array.

But if you must:

In [45]: a = np.random.normal(size=(3,3))

In [46]: a
Out[46]: 
array([[ 0.64552723, -0.4329958 , -1.84342512],
       [ 0.83197804, -0.03053034,  0.22560254],
       [ 0.61356459, -1.60778048, -1.51859134]])

In [47]: a.astype('|S8')
Out[47]: 
array([['0.645527', '-0.43299', '-1.84342'],
       ['0.831978', '-0.03053', '0.225602'],
       ['0.613564', '-1.60778', '-1.51859']], 
      dtype='|S8')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top