How to read a CSV file into a NumPy array and print it?
15. CSV to Array Conversion
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.
For more Practice: Solve these Related Problems:
- Write a Numpy program to read a CSV file into a NumPy array and then reshape the array based on metadata provided in the file.
- Write a Numpy program to import a CSV file containing mixed data types into a NumPy array while applying type conversion rules.
- Write a Numpy program to read a CSV file into a NumPy array and handle missing values by replacing them with column means.
- Write a Numpy program to load a CSV file into a NumPy array and then perform vectorized filtering to extract rows matching a criterion.
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.