How to read a CSV file into a NumPy array and print it?
NumPy: Interoperability Exercise-15 with Solution
Write a NumPy program to read a CSV file into a NumPy array and print the array.
Sample Solution:
Python Code:
import numpy as np
# Read a CSV file into a NumPy array
# Ensure the 'array.csv' file exists in the working directory
array = np.loadtxt('array.csv', delimiter=',')
# Print the NumPy array
print(array)
Output:
[[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]]
Explanation:
- Import NumPy Library: Import the NumPy library to work with arrays.
- Read CSV File into NumPy Array: Use np.loadtxt() to read the contents of a CSV file named 'array.csv' into a NumPy array, specifying the delimiter as a comma.
- Print NumPy Array: Output the resulting NumPy array to verify the data read from the CSV file.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to save a NumPy array to a CSV File and verify contents?
Next: How to convert a 3D NumPy array to a list of lists of lists?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/read-a-csv-file-into-a-numpy-array-and-print-the-array.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics