JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Writing NumPy arrays to CSV in Python

Author:JIYIK Last Updated:2025/05/04 Views:

In this tutorial, we will discuss how to store numpy arrays in CSV files.


Using pandasDataFrame to save NumPy arrays in CSV files

In this approach, we will first save the array in pandasa DataFrame and then convert it into a CSV file.

The following code shows how we can achieve this.

import pandas as pd
import numpy as np

a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
pd.DataFrame(a).to_csv("sample.csv")

pd.DataFrameThe function stores the array in a DataFrame and we just need to_csv()to export it to a CSV file using the function.


Use numpy.savetxt()the function to save NumPy arrays to CSV files

The save function in the numpy module savetxt()can save an array to a text file. We can specify the file format, delimiter, and many other parameters to get the end result in the desired format.

In the following code, we use this function to save the array in a CSV file.

import numpy as np

a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

np.savetxt("sample.csv", a, delimiter=",")

Use tofile()the function to save NumPy arrays to CSV files

tofile()The function allows us to write arrays to text or binary files. However, this method has many disadvantages. It is more of a convenience function for quickly storing array data. The accuracy of the information is lost because it stores everything in one line, so this method is not a good choice for files intended for archiving data. Some of these problems can be overcome by outputting the data as a text file at the expense of speed and file size.

The following code demonstrates the usage of this function.

import numpy as np

a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

a.tofile("sample.csv", sep=",")

Save NumPy arrays in CSV files using file processing methods

We can use traditional file processing methods, but they are not recommended because such methods require many modifications depending on the shape of the array and use a lot of memory.

The following code shows an example of this approach.

a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
csv_rows = ["{},{},{}".format(i, j, k) for i, j, k in a]
csv_text = "\n".join(csv_rows)

with open("sample.csv", "w") as f:
    f.write(csv_text)

We unpack the array into a list of rows and then join()join the list using the function to return a single string. We then write this string to the CSV file.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Enumerating a dictionary in Python

Publish Date:2025/05/05 Views:98 Category:Python

The function in Python enumerate() returns an object of enumeration type and adds a counter variable to iterate over a list or other type of collection. It makes looping over such objects easier. When we pass an enumeration object to list()

Changing dictionary values in Python

Publish Date:2025/05/05 Views:108 Category:Python

This tutorial will discuss various ways to change the value of a particular key in Python dictionary. We can do this by using the following methods. dict.update() method for cycle. Dictionary Unpacking dict.update() How to change dictionary

Finding the maximum value in a Python dictionary

Publish Date:2025/05/05 Views:60 Category:Python

This tutorial explains how to get a key with the maximum value in Python. Since the method has changed from the previous Python versions, it also lists some sample codes to clarify the concepts. Use operator.itemgetter() the method to get t

How to read input from stdin in Python

Publish Date:2025/05/05 Views:124 Category:Python

This tutorial discussed stdin the methods of reading input from in Python. You can read directly from the console or from a file name specified in the console. In Python, fileinput.input() use stdin fileinput We can use the read module in P

Maximum integer in Python

Publish Date:2025/05/05 Views:55 Category:Python

This tutorial will discuss the maximum integer value in different versions of Python and how we can get it. In Python 2, integers and long integers are different data types. The maximum value of an integer is 2 31 -1. If the value exceeds t

Get a list of time zones using Python

Publish Date:2025/05/05 Views:107 Category:Python

When developing real-world applications, software developers must ensure that the application can support users from both their own country and other parts of the world. Since most countries have different time zones and many people around

Convert NumPy array to list in Python

Publish Date:2025/05/05 Views:101 Category:Python

Lists and arrays are the two most basic and commonly used collection objects in Python. They are both mutable and are used to store a collection of elements under a common name and each element has a specific location that can be used to ac

Appending 2D Arrays in Python

Publish Date:2025/05/05 Views:64 Category:Python

In Python, we can have ND arrays. We can use NumPy module to process arrays in Python. This tutorial demonstrated the different methods you can use to append values ​​to a two-dimensional array in Python. Use append() the function to ap

Sliding average of NumPy arrays in Python

Publish Date:2025/05/05 Views:190 Category:Python

The sliding average is often used to study time series data by calculating the average of data at a specific time interval. It is used to eliminate some short-term fluctuations and study data trends. When studying stock price trends, the si

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial