Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save numpy ndarray as .csv file?

I created a numpy array as follows:

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

The values in ab are shown below:

array([(u'NAME_1',  0.1234), (u'NAME_2',  0.5678), (u'NAME_3',  0.9123)],
      dtype=[('var1', '<U6'), ('var2', '<f8')])

When I try to save ab as a .csv file using savetxt() command,

np.savetxt('D:\test.csv',ab,delimiter=',')

I get below error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-66-a71fd201aefe> in <module>()
----> 1 np.savetxt('D:\Azim\JF-Mapping-workflow-CRM\Backup\delete.csv',ab,delimiter=',')

c:\python27\lib\site-packages\numpy\lib\npyio.pyc in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments)
   1256                     raise TypeError("Mismatch between array dtype ('%s') and "
   1257                                     "format specifier ('%s')"
-> 1258                                     % (str(X.dtype), format))
   1259         if len(footer) > 0:
   1260             footer = footer.replace('\n', '\n' + comments)

TypeError: Mismatch between array dtype ('[('var1', '<U6'), ('var2', '<f8')]') and format specifier ('%.18e,%.18e')
like image 586
StatguyUser Avatar asked Feb 05 '18 12:02

StatguyUser


People also ask

How can I get data from NumPy Ndarray?

With the help of numpy. ndarray. item() method, we can fetch the data elements that is found at the given index on numpy array. Remember we can give index as one dimensional parameter or can be two dimensional.

How do I save a 3d NumPy array to CSV?

You can use the np. savetxt() method to save your Numpy array to a CSV file.


1 Answers

Your array include strings, but np default formatting is for floats.

Try manually setting the format:

np.savetxt(r'g:\test.csv',ab,delimiter=',', fmt=('%s, %f'))
like image 113
Dror Paz Avatar answered Sep 21 '22 04:09

Dror Paz