Nicolás Medina Nicolás Medina - 1 year ago 233
Python Question

numpy.column_stack with numeric and string arrays

I have several arrays, some of them have float numbers and others have string characters, all the arrays have the same length. When I try to use numpy.column_stack in these arrays, this function convert to string the float numbers, for example:

a = np.array([3.4,3.4,6.4])
b = np.array(['holi','xlo','xlo'])

B = np.column_stack((a,b))

print B
>>> [['3.4' 'holi']
['3.4' 'xlo']
['3.4' 'xlo']

>>> numpy.string

Why? It's possible to avoid it?
Thanks a lot for your time.

Answer Source

To store such mixed type data, most probably you would be required to store them as Object dtype arrays or use structured arrays. Going with the Object dtype arrays, we could convert either of the input arrays to an Object dtype upfront and then stack it alongside the rest of the arrays to be stacked. The rest of the arrays would be converted automatically to Object dtype to give us a stacked array of that type. Thus, we would have an implementation like so-


Sample run to show how to construct a stacked array and retrieve the individual arrays back -

In [88]: a
Out[88]: array([ 3.4,  3.4,  6.4])

In [89]: b
array(['holi', 'xlo', 'xlo'], 

In [90]: out = np.column_stack((a.astype(np.object),b))

In [91]: out
array([[3.4, 'holi'],
       [3.4, 'xlo'],
       [6.4, 'xlo']], dtype=object)

In [92]: out[:,0].astype(float)
Out[92]: array([ 3.4,  3.4,  6.4])

In [93]: out[:,1].astype(str)
array(['holi', 'xlo', 'xlo'], 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download