In this post, we will learn how to convert the Numpy array to CSV. This program example also works for how to write Numpy array to csv.
1. How to convert Numpy array to CSV with header
In this program example, we will learn how to use Numpy Module to save a list of lists to CSV by using numpy.savetxt() method with the below parameters.
- header : Parameter to pass columns name or header row of CSV file.
- deleimiter : is used to separate the row value by comma(,).
- fmt : %s is a %s is a single format pattern that will apply to all element of csv file.
- comments=“” : to elminate the # by default added to first column name.
Python Program
import numpy as np
List_rows=np.array([['Tom', 9, 8, 'WA'],['Trex', 6, 15, 'CA'], ['Kity', 7, 11, 'WA']])
np.savetxt("animal.csv",List_rows, delimiter =",", header='Name,Marks,Age,city',fmt ='%s',comments='')
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
2. Convert Numpy array of tuples to CSV with specific format
In this program example, we will learn how to use Numpy Module to save a list of lists to CSV by using numpy.savetxt() method with the below parameters.
- The header : Parameter to pass list of columns name.
- delimiter is used to separate the row value by comma(,).
- The fmt :We have specify datatype of each columns of numpy array and it combination of fmt=[‘%s’ , ‘%f’, ‘%d’,’%s’]
- comments=” : to elminate the # by default added to first column name.
Python Program
import numpy as np
list_Val= [ ('Tom', 9, 8, 'WA'), ('Trex', 6, 15, 'CA'), ('Kity', 7, 11, 'WA')]
dtype = [('Name', (np.str_, 10)), ('Marks', np.int32), ('weight', np.int32),('City', (np.str_, 5))]
np_array = np.array(list_Val, dtype=dtype)
np.savetxt('animal.csv', np_array, delimiter=',', fmt=['%s' , '%f', '%d','%s'], header='Name, Age, Weight, City', comments='')
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
3. Save 3D numpy Array to CSV
In this Python program example, we are writing a 3D numpy array to CSV using the NumPy module savetxt() method.
- Import the Numpy Module using import numpy as np.
- Use NumPy savetxt() method with parameters header,delimiter =”,”,fmt =’%s’,comments=”.
- It will create CSV in current directory.
Python Program
import numpy as np
List_rows=np.array([['Tom', 9, 8, 'WA'],['Trex', 6, 15, 'CA'], ['Kity', 7, 11, 'WA']])
np.savetxt("animal.csv",List_rows, delimiter =",", header='Name, Age, Weight, City',fmt ='%s',comments='')
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
4.Numpy savetxt() append
The NumPy module savetxt() method is used to append the Numpy array row at the end of the existing csv file. Let us understand with the below example how to use Numpy savetxt() to append.
Python Program Example
import numpy as np
list_rows= [ ('Tom', 9, 8, 'WA'), ('Trex', 6, 15, 'CA'), ('Kity', 7, 11, 'WA')]
list_row_append = [ ('Rack', 9, 8, 'WA'), ('Sack', 6, 15, 'CA'), ('Mack', 7, 11, 'WA')]
dtype = [('Name', (np.str_, 10)), ('Marks', np.int32), ('weight', np.int32),('City', (np.str_, 5))]
np_array = np.array(list_rows, dtype=dtype)
np_array_append = np.array(list_row_append, dtype=dtype)
with open('animal.csv','a') as csvfile:
np.savetxt(csvfile, np_array,delimiter=',',header='Name, Age, Weight, City',fmt=['%s' , '%f', '%d','%s'], comments='')
np.savetxt(csvfile,np_array_append,delimiter=',',fmt=['%s' , '%f', '%d','%s'], comments='')
Output
Name Marks Age city
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
Rack 9 8 WA
Sack 6 15 CA
Mack 7 11 WA
5. How to convert NumPy array to CSV
In the Python program code, we have imported the CSV library using code import CSV, we have two lists that we are converting to numpy array.
- List_rows : It contains nested list to write to CSV file rows.
- List_columns: To write first row that is columns or header.
The open(‘animal.csv’, ‘w’) method is used to open the CSV file in write mode. The writer() method is used to write a single row or writerows() for multiple rows.
Python Program
import numpy as np
import csv
list_rows= [ ['Tom', 9, 8, 'WA'], ['Trex', 6, 15, 'CA'], ['Kity', 7, 11, 'WA']]
List_columns = ['Name', 'Age', 'Weight', 'City']
dtype = [('Name', (np.str_, 10)), ('Marks', np.int32), ('weight', np.int32),('City', (np.str_, 5))]
np_array = np.array(list_rows)
np_array_col = np.array(List_columns)
with open('animal.csv', 'w') as csvfile:
write = csv.writer(csvfile)
write.writerow(np_array_col)
write.writerows(np_array)
Output
Name Age Weight City
Tom 9 8 WA
Trex 6 15 CA
Kity 7 11 WA
Summary
In this post, we have learned how to convert Numpy array to CSV using the below ways
- How to convert Numpy array to CSV with header
- Convert Numpy array of tuples to CSV with specific format
- Save 3D numpy Array to CSV
- Numpy savetxt() append
- How to convert NumPy array to CSV