0% found this document useful (0 votes)
6 views

Python Series Day20

Uploaded by

nagapraveen k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Series Day20

Uploaded by

nagapraveen k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python

Day – 20 Learnings

➢Read , Write Excel and CSV Files


Pandas makes it straightforward to read and write Excel and CSV files, which are common formats for
data storage and exchange.

Here’s a quick overview of how to handle these file types in Pandas.

1. Reading CSV Files


To read a CSV file into a DataFrame, use the pd.read_csv() function.

import pandas as pd

# Reading a CSV file


df = pd.read_csv('data.csv')
print(df)

Parameters:

➢ filepath: Path to the CSV file.


➢ sep: Specifies the delimiter (default is ,).
➢ header: Row to use as the header (default is the first row).
➢ usecols: Columns to read.
➢ nrows: Number of rows to read.
2. Writing CSV Files

To write a DataFrame to a CSV file, use df.to_csv().

# Writing to a CSV file


df.to_csv('output.csv', index=False)

Parameters:

➢ index=False: Prevents writing row indices in the CSV.


➢ sep: Specifies the delimiter (default is ,).
➢ header: Includes the column names if set to True.
3. Reading Excel Files

To read an Excel file, use pd.read_excel(). You’ll need openpyxl or xlrd library installed,
depending on the Excel version.

# Reading an Excel file


df = pd.read_excel('data.xlsx', sheet_name='Sheet1’)
print(df)

Parameters:

➢ sheet_name: Specifies the sheet name or index to read.


➢ usecols, nrows, and header are similar to those in read_csv().
4. Writing Excel Files

To write a DataFrame to an Excel file, use df.to_excel().

# Writing to an Excel file


df.to_excel('output.xlsx', sheet_name='Sheet1', index=False)

Parameters:

➢ sheet_name: Specifies the sheet name.


➢ index=False: Prevents writing row indices in the Excel file.
Example

import pandas as pd

# Read CSV
df_csv = pd.read_csv('data.csv')

# Perform some data manipulation


df_csv['New_Column'] = df_csv['Existing_Column'] * 2

# Save to new CSV


df_csv.to_csv('modified_data.csv', index=False)

# Read Excel
df_excel = pd.read_excel('data.xlsx', sheet_name='Sheet1')

# Save to new Excel file


df_excel.to_excel('output.xlsx', sheet_name='Results', index=False)
Summary

➢ CSV Files: Use pd.read_csv() to read and df.to_csv() to write.


➢ Excel Files: Use pd.read_excel() to read and df.to_excel() to write.

Thank you

Created by
Nagalakshmi Manne

You might also like