How to read/write data from/to a file using pandas

Published on Aug. 22, 2023, 12:17 p.m.

To read and write data from/to a file using pandas, you can use the following functions:

  1. read_csv(): This function is used to read data from a CSV file and create a pandas DataFrame object.
  2. read_excel(): This function is used to read data from an Excel file and create a pandas DataFrame object.
  3. to_csv(): This function is used to write data from a pandas DataFrame object to a CSV file.
  4. to_excel(): This function is used to write data from a pandas DataFrame object to an Excel file.

Here’s an example of how to use read_csv() and to_csv() functions to read and write data to a CSV file:

import pandas as pd

# Read data from CSV file
df = pd.read_csv('data.csv')

# Modify the DataFrame

# Write data to CSV file
df.to_csv('modified_data.csv', index=False)

In the to_csv() function, the index parameter is set to False to exclude the index column from the output file.

Similarly, you can use the read_excel() and to_excel() functions to read and write data to an Excel file.

Tags: