w3resource

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:

from numpy import genfromtxt
csv_data = genfromtxt('fdata.csv', dtype=['S10','float32','float32','float32','float32'], delimiter=",")
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)]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]