{"id":3429,"date":"2021-08-18T13:53:05","date_gmt":"2021-08-18T08:23:05","guid":{"rendered":"https:\/\/python-programs.com\/?p=3429"},"modified":"2021-11-22T18:39:34","modified_gmt":"2021-11-22T13:09:34","slug":"how-to-save-numpy-array-to-a-csv-file-using-numpy-savetxt-in-python","status":"publish","type":"post","link":"https:\/\/python-programs.com\/how-to-save-numpy-array-to-a-csv-file-using-numpy-savetxt-in-python\/","title":{"rendered":"How to save Numpy Array to a CSV File using numpy.savetxt() in Python? | Savetxt Function’s Working in Numpy with Examples"},"content":{"rendered":"
NumPy arrays are very essential data structures for working with data in Python, machine learning models. Python\u2019s 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.<\/p>\n
The Where,<\/p>\n 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.<\/p>\n 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.<\/p>\n <\/p>\n Output:<\/strong><\/p>\n 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.<\/p>\n 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<\/p>\n Usually, By default comments in both the header and footer are pre-appended by \u2018#\u2019. To change this we can pass the parameter comments like comments=\u2019@\u2019.<\/p>\n 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.<\/p>\n","protected":false},"excerpt":{"rendered":" NumPy arrays are very essential data structures for working with data in Python, machine learning models. Python\u2019s 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 …<\/p>\nnumpy.savetxt()<\/code> function is the counterpart of the NumPy
loadtxt()<\/code> function and can save arrays in delimited file formats such as CSV. Save the array we created with the following function call:<\/p>\n
Synatx : numpy.<\/span>savetxt<\/span>(<\/span>fname, array_name, fmt=<\/span>'%.18e'<\/span>, delimiter=<\/span>' '<\/span>, newline=<\/span>'\\n'<\/span>, header=<\/span>''<\/span>, footer=<\/span>''<\/span>, comments=<\/span>'# '<\/span>, encoding=<\/span>None<\/span>)<\/span><\/pre>\n
\n
<\/a>How to save Numpy Array to a CSV File using numpy.savetxt() in Python?<\/h2>\n
<\/a>Example Program on How to Save a Numpy Array to a CSV File<\/h3>\n
#Program :\r\n\r\nimport numpy as np\r\ndef main():\r\n # Numpy array created with a list of numbers\r\n array1D = np.array([9, 1, 23, 4, 54, 7, 8, 2, 11, 34, 42, 3])\r\n print('Real Array : ', array1D)\r\n print('<** Saved 1D Numpy array to csv file **>')\r\n # Save Numpy array to csv\r\n np.savetxt('array.csv', [array1D], delimiter=',', fmt='%d')\r\n print('*** Saving 1D Numpy array to csv file with Header and Footer ***')\r\n # Saving Numpy array to csv with custom header and footer\r\n np.savetxt('array_hf.csv', [array1D], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')\r\n\r\n print('*** Saving 2D Numpy array to csv file ***')\r\n # A 2D Numpy array list of list created\r\n array2D = np.array([[111, 11, 45, 22], [121, 22, 34, 14], [131, 33, 23, 7]])\r\n print('2D Numpy Array')\r\n print(array2D)\r\n # Saving 2D numpy array to csv file\r\n np.savetxt('2darray.csv', array2D, delimiter=',', fmt='%d')\r\n # Saving 2nd column of 2D numpy array to csv file\r\n np.savetxt('2darray_column.csv', [array2D[:,1]], delimiter=',', fmt='%d')\r\n # Saving 2nd row of 2D numpy array to csv file\r\n np.savetxt('2darray_row.csv', [array2D[1] ], delimiter=',', fmt='%d')\r\n\r\n # Creating the type of a structure\r\n dtype = [('Name', (np.str_, 10)), ('Marks', np.float64), ('GradeLevel', np.int32)]\r\n #Creating a Strucured Numpy array\r\n structuredArr = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6), ('Riti', 88.8, 7)], dtype=dtype)\r\n print(structuredArr)\r\n # Saving 2D numpy array to csv file\r\n np.savetxt('struct_array.csv', structuredArr, delimiter=',', fmt=['%s' , '%f', '%d'], header='Name,Marks,Age', comments='')\r\nif __name__ == '__main__':\r\n main()<\/pre>\n
Real Array :\u00a0 [ 9\u00a0 1 23\u00a0 4 54\u00a0 7\u00a0 8\u00a0 2 11 34 42\u00a0 3]\r\n<** Saved 1D Numpy array to csv file **>\r\n<** Saved 1D Numpy array to csv file with custom\u00a0 Header and Footer **>\r\n<** Save 2D Numpy array to csv file **>\r\n* 2D Numpy Array *\r\n[[111\u00a0 11\u00a0 45\u00a0 22]\r\n[121\u00a0 22\u00a0 34\u00a0 14]\r\n[131\u00a0 33\u00a0 23\u00a0\u00a0 7]]\r\n[('Rags', 33.3, 3) ('Punit', 44.4, 5) ('Drishti', 66.6, 6)\u00a0 ('Ritu', 88.8, 7)]<\/pre>\n
<\/a>Save 1D Numpy array to CSV file with Header and Footer<\/h3>\n
# Save Numpy array to csv with custom header and footer\r\nnp.savetxt('array_hf.csv', [arr], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')<\/pre>\n
Final Words<\/h3>\n