Categories: NumpyPython

How to read csv file using Numpy in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

Numpy module has a function genfromtxt() that is used to read tabular data format into an array. The option for the function is the file name in working directory, delimiter and first line as variable name. The following example shows how to read a csv file into an structured array.

#a csv file in working directory
index,gender,math,physics,chemistry
16,male,29,98,83,76
17,female,36,73,79,69
18,male,39,71,73,87
19,female,24,68,72,89
20,female,25,67,73,62
#Import Numpy module
import numpy as np
#read csv file, create an structured array, 
#delimiter using comma, and first line in the file as variable name
score = np.genfromtxt('score.csv', delimiter=',', names=True)
score
#output
array([(16,male,29,98,83,76), (17,female,36,73,79,69),
(18,male,39,71,73,87),(19,female,24,68,72,89),(20,female,25,67,73,62)],
dtype=[('index', '<i2'), ('gender', 'S6'), ('math', '<i4'), ('physics', '<i4'),
('chemistry', '<i4')])

You can see Numpy returns as a structured array.

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Fine tuning a Hugging Face transformer model for multi-track music generation

To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…

3 weeks ago

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

3 weeks ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 weeks ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

3 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

12 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago