. Advertisement .
..3..
. Advertisement .
..4..
Computers are mostly used to store information and extract information from it. Python is one of the most powerful programming languages. We can use Python to get computers to do most of the routine processes. This blog is all about how we can use Python to write Numpy Array to CSV.
How Can You Write Numpy Array to CSV in Python?
Approach 1: Utilize savetext()
You can utilize savetext() to write Numpy array to CSV in Python. Let’s take a look at an example of this:
import numpy as np
a = np.asarray([ [38,32,45], [12,24,26], [4,16,64] ])
np.savetxt('sample.csv', a, delimiter=",")
Approach 2: Utilize tofile()
Another way is utilizing tofile() as the following example:
import numpy as np
arr1 = np.asarray([ [38,32,45], [12,24,26], [4,16,64] ])
arr1.tofile('sample.csv',sep=',')
Approach 3: Utilize a pandas DataFrame
In this way, the array need to be saved in a pandas DataFrame first, then it will be converted to a CSV file. The following example describes how we can obtain 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')
The array is stored in a DataFrame by the pd.DataFrame function, and we just export it to a CSV file using the to csv() function.
Approach 4: Utilize File Solving Methods
We can utilize traditional file management method to write Numpy array to CSV in Python. However, they can be memory intensive and necessitate numerous modifications depending on the shape of the array.
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)
The array is unpacked into a list of rows, which is then joined using the join() function to produce a single string. The string is then saved as a CSV file.
Conclusion
Writing Numpy Array to CSV in Python is a confusing problem. We hope this blog has helped clear the air around how to do it. If you have more questions about this topic, please leave a comment below. Thank you for reading; we are always excited when one of our posts can provide useful information on a topic like this!
Read more
Leave a comment