NumPy: Read a CSV data file and store records in an array
NumPy: Array Object Exercise-105 with Solution
Write a NumPy program to read a CSV data file and store records in an array.
Sample CSV file: fdata.csv
Date,Open,High,Low,Close
03-10-16,774.25,776.065002,769.5,772.559998
04-10-16,776.030029,778.710022,772.890015,776.429993
05-10-16,779.309998,782.070007,775.650024,776.469971
06-10-16,779,780.47998,775.539978,776.859985
07-10-16,779.659973,779.659973,770.75,775.080017
Sample Solution:
Python Code:
# Importing the 'genfromtxt' function from the NumPy library
from numpy import genfromtxt
# Loading data from the CSV file 'fdata.csv' using 'genfromtxt'
# 'dtype' specifies the data types for columns: a string of maximum length 10, and four columns of float32 data type
# 'delimiter=","' specifies the delimiter in the CSV file as a comma ","
csv_data = genfromtxt('fdata.csv', dtype=['S10', 'float32', 'float32', 'float32', 'float32'], delimiter=",")
# Printing the data loaded from the CSV file
print(csv_data)
Sample Output:
[(b'Date', nan, nan, nan, nan) (b'03-10-16', 774.25, 776.065, 769.5 , 772.56) (b'04-10-16', 776.03, 778.71 , 772.89, 776.43) (b'05-10-16', 779.31, 782.07 , 775.65, 776.47) (b'06-10-16', 779. , 780.48 , 775.54, 776.86) (b'07-10-16', 779.66, 779.66 , 770.75, 775.08)]
Explanation:
In the above code -
csv_data = genfromtxt('fdata.csv', dtype=['S10','float32','float32','float32','float32'], delimiter=","): Use the genfromtxt function to read data from the file named 'fdata.csv'. The dtype parameter specifies the data types for each column in the file. In this case, the first column has a string data type with a maximum length of 10 bytes ('S10'), and the other four columns have 32-bit float data types ('float32'). The delimiter parameter specifies that the columns in the file are separated by commas.
Finally print() function prints the resulting array containing the data from the CSV file.
Python-Numpy Code Editor:
Previous: Write a NumPy program to access last two columns of a multidimensional columns.
Next: Write a NumPy program to count the occurrence of a specified item in a given NumPy array.
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/python-numpy-exercise-105.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics