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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics