15.1 C
London
Friday, July 5, 2024
HomePandas in PythonInput/Output in PythonHow to Read CSV File with NumPy (Step-by-Step)

How to Read CSV File with NumPy (Step-by-Step)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to read a CSV file into a record array in NumPy:

from numpy import genfromtxt

my_data = genfromtxt('data.csv', delimiter=',', dtype=None)

The following step-by-step example shows how to use this syntax in practice.

Step 1: View the CSV File

Suppose we have the following CSV file called data.csv that we’d like to read into NumPy:

Step 2: Read in CSV File

The following code shows how to read in this CSV file into a Numpy array:

from numpy import genfromtxt

#import CSV file
my_data = genfromtxt('data.csv', delimiter=',', dtype=None)

Note the following:

  • delimiter: This specifies the delimiter that separates the data values in the CSV file.
  • dtype: This specifies the data type for the NumPy array. By using None, we allow multiple data types to be imported at once within the array.

Example 3: View the NumPy Array

Once we’ve imported the CSV file, we can view it:

#view imported CSV file
my_data

array([[1, 2, 2, 2, 3, 4],
       [5, 5, 6, 8, 9, 9]])

We can see that the data in the NumPy array matches the data shown in the CSV file.

Note: You can find the complete online documentation for the genfromtxt() function here.

Additional Resources

The following tutorials explain how to perform other common functions with CSV files in pandas:

How to Read CSV Files with Pandas
How to Export Pandas DataFrame to CSV File
Pandas: How to Append Data to Existing CSV File

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories