Python save numpy array to csv

How to Write NumPy Arrays to CSV Files

This post explains how to write NumPy arrays to CSV files.

  • the syntax for writing different NumPy arrays to CSV
  • the limitations of writing NumPy arrays to CSV
  • alternative ways to save NumPy arrays

Writing NumPy Arrays to CSV

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

If you don’t use these two settings, NumPy will save your files as .txt. More on that later.

CSV files can be great because they are human-readable. They also have the added benefit of being easy to load into pandas or Dask DataFrames.

Читайте также:  Язык java является только интерпретируемым

Write one dimensional array

Let’s create a one-dimensional array containing random numbers using np.random.rand() .

import numpy as np 
# create 1D array
a = np.array([1,2,3])
# store in current directory
np.savetxt( "a.csv", a, delimiter="," )

NumPy will write the array column-wise by default. Let’s inspect the contents of a.csv to confirm:

To write the data row-wise instead, set the newline kwarg to «,» (your delimiter).

# write array row-wise 
np.savetxt("very.csv", a, delimiter=",", newline=",")

You can also write the array row-wise by converting it to a 2D array first

np.savetxt("very.csv", [a], delimiter="," )

In both cases, the content of very.csv will look like this:

Write two dimensional array

Let’s now create a two-dimensional NumPy array and save it to CSV.

# create 2D array 
b = np.array([1, 2, 3], [4, 5, 6])
# write 2D array to CSV…

Источник

How To Write Numpy Array To A CSV file In Python – Definitive Guide

Stack Vidhya

This tutorial teaches you the different methods to write NumPy array to a CSV file in Python and when it is appropriate to use them.

Using NumPy Savetxt

The savetxt() method writes the NumPy array into a CSV file.

  • Pass the CSV file name, array and the delimiter to delimit the data.
  • It writes data in “%.18e” format by default if the fmt parameter is not specified.

Use this method when you want to save the array in a CSV file and want the data in the “%.18e” format to maintain the precision of the data.

import numpy as np numpyArr = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) np.savetxt('myArrayAsCSV.csv', numpyArr, delimiter=",")
1.000000000000000000e+00,2.000000000000000000e+00,3.000000000000000000e+00 4.000000000000000000e+00,5.000000000000000000e+00,6.000000000000000000e+00 7.000000000000000000e+00,8.000000000000000000e+00,9.000000000000000000e+00

Using NumPy Savetxt with Format Specification

This section teaches you how to use the savetxt() method with the format specification.

It is specifically useful when you want to format the data with fewer decimals or in a string format.

  • Use the fmt parameter and specify the format. A string or a sequence of formats. Example: “%d” to format the numbers as decimals instead of float.

Use this method when you want to store the numpy array data in a decimal or a string format.

import numpy as np numpyArr = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) np.savetxt('myArrayAsCSV.csv', numpyArr, fmt="%d", delimiter=",")

Using Numpy To_File

The to_file() method writes the numpy array as a text file or a binary file.

  • It is a useful and convenient method for quick storage of the array of data.
  • It doesn’t store the endianness, and precision is lost.
  • Hence, it is not recommended to use it to create files for data archival or data transportation purposes.

Use this method when you want to store and retrieve the array data quickly and don’t want to retain the precision of the data.

import numpy as np numpyArr = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) numpyArr.tofile('myArrayAsCSV.csv',sep=',',format="%d")

Save Numpy Array to CSV with Headers

To convert the numpy array to a CSV file with headers,

  • Use the savetxt() method
  • Use the header parameter with the list of headers. The length of the headers must be equal to the number of columns in the array
  • Pass the comments=“” parameter to avoid # at the beginning of the header information
import numpy as np numpyArr = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) numpyArr.tofile('myArrayAsCSV.csv',sep=',',format="%d") np.savetxt("myArrayAsCSV.csv", numpyArr, delimiter=",", fmt="%d", header="A, B, C", comments="")

This is how you can dump a NumPy array into a CSV file with headers.

Additional Resources

Источник

Save numpy array as csv – How to save Numpy Array to a CSV File using numpy.savetxt() in Python? | Savetxt Function’s Working in Numpy with Examples

How to save Numpy Array to a CSV File using numpy.savetxt() in Python

Save numpy array as csv: NumPy arrays are very essential data structures for working with data in Python, machine learning models. Python’s Numpy module provides a function to save a numpy array to a txt file with custom delimiters and other custom options. In this tutorial, we will discuss the procedure of how to save Numpy Array to a CSV File with clear steps.

numpy.savetxt() Function

Save numpy array to csv: The numpy.savetxt() function is the counterpart of the NumPy loadtxt() function and can save arrays in delimited file formats such as CSV. Save the array we created with the following function call:

Synatx : numpy.savetxt(fname, array_name, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
  • fname: If the filename ends in .gz, the file is automatically saved in compressed gzip format. The loadtxt() function can understand gzipped files transparently.
  • arr_name: It indicates data to be saved like 1D or 2D numpy array.
  • fmt: It refers to a formatting pattern or sequence of patterns, which will be used while saving elements to file.
  • delimiter: It is optional, refers to string or character to be used as element separator
  • newline: It is optional, refers to string or character to be used as line separator
  • header: It refers to a string that is written at the beginning of the file.
  • footer: It refers to a string that to be written at the end of the txt file.
  • comments: It refers to a custom comment marker, where the default is ‘#’. It will be pre-appended to the header and footer.

How to save Numpy Array to a CSV File using numpy.savetxt() in Python?

Numpy save to CSV: One of the most common file formats for storing numerical data in files is the comma-separated variable format or CSV in Short. Usually, input data are stored in CSV Files as it is one of the most convenient ways for storing data.

Savetxt function is used to save Numpy Arrays as CSV Files. The function needs a filename and array as arguments to save an array to CSV File. In addition, you need to mention the delimiter; for separating each variable in the file or most commonly comma. You can set via the “delimiter” argument.

Example Program on How to Save a Numpy Array to a CSV File

#Program : import numpy as np def main(): # Numpy array created with a list of numbers array1D = np.array([9, 1, 23, 4, 54, 7, 8, 2, 11, 34, 42, 3]) print('Real Array : ', array1D) print('<** Saved 1D Numpy array to csv file **>') # Save Numpy array to csv np.savetxt('array.csv', [array1D], delimiter=',', fmt='%d') print('*** Saving 1D Numpy array to csv file with Header and Footer ***') # Saving Numpy array to csv with custom header and footer np.savetxt('array_hf.csv', [array1D], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer') print('*** Saving 2D Numpy array to csv file ***') # A 2D Numpy array list of list created array2D = np.array([[111, 11, 45, 22], [121, 22, 34, 14], [131, 33, 23, 7]]) print('2D Numpy Array') print(array2D) # Saving 2D numpy array to csv file np.savetxt('2darray.csv', array2D, delimiter=',', fmt='%d') # Saving 2nd column of 2D numpy array to csv file np.savetxt('2darray_column.csv', [array2D[:,1]], delimiter=',', fmt='%d') # Saving 2nd row of 2D numpy array to csv file np.savetxt('2darray_row.csv', [array2D[1] ], delimiter=',', fmt='%d') # Creating the type of a structure dtype = [('Name', (np.str_, 10)), ('Marks', np.float64), ('GradeLevel', np.int32)] #Creating a Strucured Numpy array structuredArr = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6), ('Riti', 88.8, 7)], dtype=dtype) print(structuredArr) # Saving 2D numpy array to csv file np.savetxt('struct_array.csv', structuredArr, delimiter=',', fmt=['%s' , '%f', '%d'], header='Name,Marks,Age', comments='') if __name__ == '__main__': main()

Python Program for Saving Numpy Array to a CSV File

Real Array : [ 9 1 23 4 54 7 8 2 11 34 42 3] <** Saved 1D Numpy array to csv file **> <** Saved 1D Numpy array to csv file with custom Header and Footer **> <** Save 2D Numpy array to csv file **>* 2D Numpy Array * [[111 11 45 22] [121 22 34 14] [131 33 23 7]] [('Rags', 33.3, 3) ('Punit', 44.4, 5) ('Drishti', 66.6, 6) ('Ritu', 88.8, 7)]

The Passed Delimeter ‘,’ will change to CSV Format. In addition, the format string %d passed will store the elements as integers. By default, it will store numbers in float format. Keep in mind that if you don’t mention [] around numpy array to change it to list while passing numpy.savetxt() comma delimiter willn’t work and uses ‘\n’ by default. Thus, surrounding array by [] i.e. [arr] is mandatory.

Save 1D Numpy array to CSV file with Header and Footer

Python save array to csv: In order to add comments to the header and footer while saving to a CSV File, we can pass the Header and Footer Parameters as such

# Save Numpy array to csv with custom header and footer np.savetxt('array_hf.csv', [arr], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')

Usually, By default comments in both the header and footer are pre-appended by ‘#’. To change this we can pass the parameter comments like comments=’@’.

Final Words

Numpy savetxt can be an extremely helpful method for saving an array to CSV File. If you want to manipulate or change the existing data set this can be a great method. If you have any queries don’t hesitate to ask us via comment box so that we can get back to you at the soonest possible. Bookmark our site for the latest updates on Python, Java, C++, and Other Programming Languages.

Источник

Как экспортировать массив NumPy в файл CSV (с примерами)

Как экспортировать массив NumPy в файл CSV (с примерами)

Вы можете использовать следующий базовый синтаксис для экспорта массива NumPy в файл CSV:

import numpy as np #define NumPy array data = np.array([[1,2,3],[4,5,6],[7,8,9]]) #export array to CSV file np.savetxt (" my_data.csv", data, delimiter=" , ") 

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: экспорт массива NumPy в CSV

В следующем коде показано, как экспортировать массив NumPy в файл CSV:

import numpy as np #define NumPy array data = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12], [13, 14, 15]]) #export array to CSV file np.savetxt (" my_data.csv", data, delimiter=" , ") 

Если я перейду к месту, где файл CSV сохранен на моем ноутбуке, я смогу просмотреть данные:

Пример 2: экспорт массива NumPy в CSV в определенном формате

Формат чисел по умолчанию — «%.18e» — это отображает 18 нулей. Однако мы можем использовать аргумент fmt для указания другого формата.

Например, следующий код экспортирует массив NumPy в CSV и указывает два десятичных разряда:

import numpy as np #define NumPy array data = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12], [13, 14, 15]]) #export array to CSV file (using 2 decimal places) np.savetxt (" my_data.csv", data, delimiter=" ,", fmt=" %.2f ") 

Если я перейду к месту, где сохранен файл CSV, я смогу просмотреть данные:

Пример 3: экспорт массива NumPy в CSV с заголовками

В следующем коде показано, как экспортировать массив NumPy в файл CSV с пользовательскими заголовками столбцов:

import numpy as np #define NumPy array data = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12], [13, 14, 15]]) #export array to CSV file (using 2 decimal places) np.savetxt (" my_data.csv", data, delimiter=" ,", fmt=" %.2f", header=" A, B, C", comments="") 

Примечание.Аргумент комментариев предотвращает отображение символа «#» в заголовках.

Если я перейду к месту, где сохранен файл CSV, я смогу просмотреть данные:

Примечание.Полную документацию по функции numpy.savetxt() можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции чтения и записи в Python:

Источник

Оцените статью