In this Python tutorial, we will learn the Python write array to CSV, and also we will cover these topics:
- How to write Python array to CSV file
- Python write array to CSV row
- Python write array to CSV header
- Python write array to CSV file using np.arange
- Python write array to CSV file using numpy.savetxt
- Python write byte literals to CSV file
- Python write 2Darray to CSV file
- Python write 3D array to CSV file
Python write array to CSV
Here, we can see how to write an array to csv file in python.
- In this example, I have imported a module called pandas as pd and numpy as np.
- Then declared a variable as an array and assigned array = np.arange(1,21).reshape(4,5).
- The arange is an inbuilt numpy package that returns nd array objects, The(1,21) is the range given, and reshape(4,5) is used to get the shape of an array.
- A data frame is a 2-dimensional data structure, data is aligned in the tabular fashion of rows and columns.
- The pd.DataFrame(array) is the panda’s data frame and this is a two-dimensional mutable heterogeneous tabular data structure with rows and columns.
- To pass the value to csv file dataframe.to_csv(r”C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\data1.csv”) is used.
- The path of the file and the name of the file is used, data1.csv is the file name.
Example:
import pandas as pd
import numpy as np
array = np.arange(1,21).reshape(4,5)
dataframe = pd.DataFrame(array)
dataframe.to_csv(r"C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\data1.csv")
You can see that the array is stored in the CSV file as the output. You can refer to the below screenshot for the output.
Python write array to CSV row
Now, we can see how to write array to CSV row in python.
- In this example, I have imported a module called CSV and numpy as np. The CSV file is the most used flat-file used to store and hare data across platforms.
- I have taken a variable as array and assigned array = [[‘welcome’], [‘to’], [‘pythonguides !’]].
- file = open(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\site.csv’, ‘w+’, newline =”) this is the path and site.csv is the file name.
- The write = csv.writer(file) is used to create the write object and the write row is used to write the single rows to the file.
Example:
import csv
import numpy as np
array = [['welcome'], ['to'], ['pythonguides !']]
file = open(r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\site.csv', 'w+', newline ='')
with file:
write = csv.writer(file)
write.writerows(array)
The output can be seen in row format in the below screenshot.
Python write array to CSV header
Here, we can see how to write array to csv header in python.
- In this example, I have imported a module called numpy as np and taken a variable called array = np.array([2 ,4, 6, 8, 10]).
- The np.array is used to create an array and another variable newfile is created, and assigned newfile = np.savetxt(“header.csv”, np.dstack((np.arange(1, array.size+1),array))[0],”%d,%d”,header=”Id,Values”).
- The np.savetxt is used to save an array to the file, the header.csv is the name of the file.
- The np.dstack is the function used for array up to 3 dimensions to get the size of an array, I have used (1, array.size+1),array)) [0].
- The %d is used for the place holder header=”Id,Values” is used to get the value of number along with the header. To get the output, I have used print(newfile).
Example:
import numpy as np
array = np.array([2 ,4, 6, 8, 10])
newfile = np.savetxt("header.csv", np.dstack((np.arange(1, array.size+1),array))[0],"%d,%d",header="Id,Values")
print(newfile)
Here, we can see the values along with the header id = header and value = value. You can refer to the below screenshot for the output.
Python write array to CSV file using np.arange
Now, we can see how to write array to ccsv file using np.arange in python.
- In this example, I have imported a module called numpy as np and created a variable called an array, and assigned array = np.arange(1,20).
- The np.arange is used to create an array with the range, (1,20) is the given range.
- The array.tofile is used to write all the items to the file object, ‘hello.csv’ is the name of the file sep = ‘,’ is the separator.
Example:
import numpy as np
array = np.arange(1,20)
print(array)
array.tofile('hello.csv', sep = ',')
The number between the given range is show in the below screenshot as the output.
Python write array to CSV file using numpy.savetxt
Here, we can how to write array to csv file using numpy.savetxt in python
- In this example, I have imported a module called numpy and created a variable as array and assigned array = numpy.array([[2, 4, 6],[8, 10, 12],[14, 16, 18]]).
- I have used numpy.savetxt(“even.csv”, a, delimiter = “,”), the savetxt is the function of numpy used to save numpy array to file.
- The delimiter is a sequence of characters used to specify the boundary between separate.
Example:
import numpy
array = numpy.array([[2, 4, 6],
[8, 10, 12],
[14, 16, 18]])
numpy.savetxt("even.csv", array, delimiter = ",")
You can refer to the below screenshot for the output:
Python write byte literals to CSV file
Here, we can see how to write byte literals to csv file in python.
- In this example, I have imported modules like CSV and open a file called bytes.csv and used “w” mode to write the file, and newline=” ” is used to put the data in a new line,
- And then assigned byte = b’\xb25′ and to encode that byte, I have called another variable as encode as assigned as encode = byte.decode(“iso-8859-1”).
- To write to the CSV file I have used csv.writer(file) to write the rows to the file of encoded value I have used file.writerow([encode]).
Example:
import csv
with open("bytes.csv", "w", newline="") as csvfile:
byte = b'\xb25'
encode = byte.decode("iso-8859-1")
file = csv.writer(csvfile)
file.writerow([encode])
The byte literal value is stored in the csv file format. You can refer to the below screenshot for the output:
Python write 2Darray to CSV file
Here, we can see how to write 2Darray to CSV file in python
- In this example, I have imported a module called csv and variable is created as array_2D as array_2D = [[3,6,9,12],[4,8,12,16]] .
- To open the file I have used with open(“array.csv”,”w+”) as my_csv: The array.csv is the name of the file “w+” is the mode used to write the file.
- Another variable new array is called as newarray = csv.writer(my_csv,delimiter=’,’). The CSV writer is used to insert the data into a CSV file.
- The delimiter is a sequence of characters used to specify the boundary between separate.
- The newarray.writerows(array_2D) is used to write each row in the csv file.
Example:
import csv
array_2D = [[3,6,9,12],[4,8,12,16]]
with open("array.csv","w+") as my_csv:
newarray = csv.writer(my_csv,delimiter=',')
newarray.writerows(array_2D)
In the below screenshot you can see that the 2D array is stored in the csv file. You can refer to the below screenshot for the output.
Python write 3D array to CSV file
Here, we can see how to write 3Darray to CSV file in python
- In this example, I have imported a module called csv and variable is created as array_3D as array_2D = [[3,6,9,12],[4,8,12,16],[5,10,15,20]].
- To open the file I have used with open(“array.csv”,”w+”) as my_csv: The array.csv is the name of the file “w+” is the mode used to write the file.
- Another variable new array is called as newarray = csv.writer(my_csv,delimiter=’,’). The CSV writer is used to insert the data into a CSV file.
- The delimiter is a sequence of characters used to specify the boundary between separate.
- The newarray.writerows(array_3D) is used to write each row in the CSV file.
Example:
import csv
array_3D = [[3,6,9,12],[4,8,12,16],[5,10,15,20]]
with open("array_3D.csv","w+") as my_csv:
newarray = csv.writer(my_csv,delimiter=',')
newarray.writerows(array_3D)
In the below screenshot you can see the output as the 3D array is stored in the csv file.
You may like the following Python tutorials:
- Python shape of an array
- How to Convert Python string to byte array with Examples
- Create an empty array in Python
- Python read a binary file
- Python File methods (With Useful Examples)
- How to make a matrix in Python
- Python Tkinter Window Size
- Check if a list exists in another list Python
In this tutorial, we have learned about the Python write array to CSV file, and also we have covered these topics:
- Python write array to CSV file
- Python write array to CSV row
- Python write array to CSV header
- Python write array to CSV file using np.arange
- Python write array to CSV file using numpy.savetxt
- Python write byte literals to CSV file
- Python write 2Darray to CSV file
- Python write 3D array to CSV file
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.