Read All Values in a Row Except the First Value for a Csv File Python

Intro: In this article, I will walk you through the different means of reading and writing CSV files in Python.

Table of Contents:

  1. What is a CSV?
  2. Reading a CSV
  3. Writing to a CSV

1. What is a CSV?

CSV stands for "Comma Separated Values." Information technology is the simplest form of storing data in tabular form as plain text. It is important to know to work with CSV because nosotros mostly rely on CSV data in our day-to-mean solar day lives as information scientists.

Structure of CSV:

We accept a file named "Salary_Data.csv." The first line of a CSV file is the header and contains the names of the fields/features.

Later on the header, each line of the file is an ascertainment/a tape. The values of a record are separated by "comma."

2. Reading a CSV

CSV files can be handled in multiple ways in Python.

2.1 Using csv.reader

Reading a CSV using Python'southward inbuilt module chosen csv using csv.reader object.

Steps to read a CSV file:

one. Import the csv library

import csv

2. Open the CSV file

The .open() method in python is used to open files and render a file object.

file = open up('Salary_Data.csv')  blazon(file)

The type of file is "_io.TextIOWrapper" which is a file object that is returned past the open() method.

3. Use the csv.reader object to read the CSV file

csvreader = csv.reader(file)

four. Excerpt the field names

Create an empty list called header. Apply the next() method to obtain the header.

The .next() method returns the current row and moves to the next row.

The first time you run next() it returns the header and the next time you run it returns the offset tape and so on.

header = [] header = next(csvreader) header

5. Extract the rows/records

Create an empty list chosen rows and iterate through the csvreader object and append each row to the rows listing.

rows = [] for row in csvreader:         rows.suspend(row) rows

6. Close the file

.shut() method is used to close the opened file. Once information technology is closed, we cannot perform any operations on it.

file.close()

Complete Code:

import csv file = open("Salary_Data.csv") csvreader = csv.reader(file) header = next(csvreader) impress(header) rows = [] for row in csvreader:     rows.append(row) impress(rows) file.close()

Naturally, we might forget to shut an open up file. To avert that we can use the with()statement to automatically release the resource. In simple terms, there is no demand to telephone call the .shut() method if we are using with() statement.

Implementing the to a higher place code using with() statement:

Syntax: with open up(filename, mode) as alias_filename:

Modes:

'r' – to read an existing file,
'westward' – to create a new file if the given file doesn't be and write to it,
'a' – to append to existing file content,
'+' –  to create a new file for reading and writing

import csv rows = [] with open("Salary_Data.csv", 'r) as file:     csvreader = csv.reader(file)     header = next(csvreader)     for row in csvreader:         rows.append(row) print(header) print(rows)

2.2 Using .readlines()

Now the question is – "Is information technology possible to fetch the header, rows using simply open() and with() statements and without the csv library?" Let's meet…

.readlines() method is the answer. It returns all the lines in a file as a list. Each particular of the list is a row of our CSV file.

The first row of the file.readlines() is the header and the residue of them are the records.

with open up('Salary_Data.csv') as file:     content = file.readlines() header = content[:1] rows = content[one:] print(header) print(rows)

**The 'n' from the output can be removed using .strip() method.

What if we have a huge dataset with hundreds of features and thousands of records. Would it exist possible to handle lists??

Here comes the pandas library into the film.

2.3 Using pandas

Steps of reading CSV files using pandas

ane. Import pandas library

import pandas as pd

2. Load CSV files to pandas using read_csv()

Basic Syntax: pandas.read_csv(filename, delimiter=',')

data= pd.read_csv("Salary_Data.csv") data

3. Extract the field names

.columns is used to obtain the header/field names.

data.columns

4. Extract the rows

All the data of a information frame can be accessed using the field names.

data.Salary

3. Writing to a CSV file

We can write to a CSV file in multiple ways.

3.ane Using csv.author

Let'southward assume we are recording 3 Students data(Name, M1 Score, M2 Score)

header = ['Name', 'M1 Score', 'M2 Score'] information = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]]

Steps of writing to a CSV file:

i. Import csv library

import csv

ii. Define a filename and Open up the file using open up()

three. Create a csvwriter object using csv.writer()

4. Write the header

v. Write the rest of the data

code for steps ii-5

filename = 'Students_Data.csv' with open(filename, 'w', newline="") as file:     csvwriter = csv.writer(file) # 2. create a csvwriter object     csvwriter.writerow(header) # 4. write the header     csvwriter.writerows(information) # 5. write the residuum of the data

Beneath is how our CSV file looks.

3.2 Using .writelines()

Iterate through each list and convert the list elements to a string and write to the csv file.

header = ['Proper noun', 'M1 Score', 'M2 Score'] data = [['Alex', 62, fourscore], ['Brad', 45, 56], ['Joey', 85, 98]] filename = 'Student_scores.csv' with open up(filename, 'w') every bit file:     for header in header:         file.write(str(header)+', ')     file.write('n')     for row in data:         for x in row:             file.write(str(x)+', ')         file.write('n')

3.3. Using pandas

Steps to writing to a CSV using pandas

i. Import pandas library

import pandas every bit pd

two. Create a pandas dataframe using pd.DataFrame

Syntax: pd.DataFrame(data, columns)

The information parameter takes the records/observations and the columns parameter takes the columns/field names.

header = ['Proper name', 'M1 Score', 'M2 Score'] information = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]] information = pd.DataFrame(data, columns=header)

3. Write to a CSV file using to_csv()

Syntax: DataFrame.to_csv(filename, sep=',', index=False)

**separator is ',' by default.

index=Faux to remove the index numbers.

data.to_csv('Stu_data.csv', index=Imitation)

Below is how our CSV looks like

Terminate Notes:

Give thanks you for reading till the determination. By the end of this article, we are familiar with different ways of handling CSV files in Python.

I hope this article is informative. Feel free to share it with your study buddies.

References:

Cheque out the complete code from the GitHub repo.

Other Blog Posts past me

Feel costless to check out my other blog posts from my Analytics Vidhya Profile.

Yous tin find me on LinkedIn, Twitter in case you would want to connect. I would exist glad to connect with you.

For immediate exchange of thoughts, please write to me at [e-mail protected].

The media shown in this article are not owned by Analytics Vidhya and are used at the Author'southward discretion.

Read All Values in a Row Except the First Value for a Csv File Python

Source: https://www.analyticsvidhya.com/blog/2021/08/python-tutorial-working-with-csv-file-for-data-science/

0 Response to "Read All Values in a Row Except the First Value for a Csv File Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel