Pandas Pandas input output

DataFrame to CSV file by to_csv() We will save data to CSV ( comma separated values ) file. This is a format used for storing data which can easily exported to MS Excel or any other database.
import pandas as pd 
my_data = pd.DataFrame(data=my_dict)
Returns None if path of csv file is given and returns the string in CSV format if path is not given.
Python Pandas DataFrame to creating csv file and using MySQL sample table to csv by using to_csv()

By default we will have index as left most column. We can remove index by using option index=False

Storing Path

We can keep in D drive ( root )
Inside data directory

Separator sep

By default sep="," , This is one char length string used to separate data in a row.

na_rep Blank data

How to handle if data is blank, we can use na_rep='*'


By default it will add the index to csv file as extra column, we can set the value to False to remove the index column.


We can restric the columns by specifying the column names as a list.


We can remove the column names and store only the data part. By default it is True and all column headers are used.

Storing part of the data

We can filter the DataFrame and then save the rows in CSV file. For this we will use our test.csv file as we have more rows.
Now let us store only two columns, class and name
import pandas as pd 
my_data = pd.DataFrame(data=df)
We can use various other filters to manage the data and store in CSV file. You can rad more on filters sections.

Data from MySQL table to CSV file

Read on how to connect to MySQL database and then collected the records of student table by using read_sql() to a DataFrame. Finally we will save them in an CSV file using to_csv().
import mysql.connector
import pandas as pd 
my_connect = mysql.connector.connect(
####### end of connection ####
sql="SELECT * FROM student "
my_data = pd.read_sql(sql,my_connect )

Using SQLAlchemy

Read more on MySQL with SQLAlchemy connection. Below code will create student.csv file in the same directory, you can add path ( as above ) if you want the file to be created at different location.
import pandas as pd 
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/my_db")
sql="SELECT * FROM student "
my_data = pd.read_sql(sql,my_conn)
my_data.to_csv('student.csv') # Add the path 


Data input and output from Pandas DataFrame
Pandas read_csv() read_excel() to_excel() to_string()

Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 All rights reserved worldwide Privacy Policy Disclaimer