Python Pandas DataFrame to creating csv file and using MySQL sample table to csv by using to_csv()

Published: 07 May 2021
on channel: plus2net
1,386
15

We can create a csv ( Comma Separated Value ) file by using data from Pandas DataFrame. We will first create one Pandas DataFrame by using some sample data.
https://www.plus2net.com/python/panda...

import pandas as pd
my_dict={'NAME':['Alex','Ron','Ravi'],
'ID':[1,2,3],
'MATH':[40,35,48]}
my_data=pd.DataFrame(data=my_dict)

After creating the DataFrame we will use to_csv() to create a CSV file
my_data.to_csv('my_file.csv')

This will create the my_file.csv file in the same directory. A different path can be given to store the file in different location in the system.
We can add different options while creating the CSV file and some important options are header, index and columns.
By setting index=False we can remove the index column and by setting header=False we can remove the header column. Similarly we can specify the columns to be used to crate CSV file, by default all columns are used.

From MySQL database using read_sql()
We can connect to MySQL database by using SQLAlchemy engine and after connection we will create our DataFrame by using data from sample table by using read_sql.
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
sql="SELECT * FROM student LIMIT 0,10"
my_data=pd.read_sql(sql,my_conn)
my_data.to_csv('my_file.csv')

Here 10 rows of data from the student table is taken and the csv file is created.
#pandas_to_csv #dataframetocsv #pandascsv


On this page of the site you can watch the video online Python Pandas DataFrame to creating csv file and using MySQL sample table to csv by using to_csv() with a duration of hours minute second in good quality, which was uploaded by the user plus2net 07 May 2021, share the link with friends and acquaintances, this video has already been watched 1,386 times on youtube and it was liked by 15 viewers. Enjoy your viewing!