Pandas to_csv - Pandas Save Dataframe to CSV file - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how we can save pandas dataframe to CSV file (comma separated values).
The to_csv() method of pandas will save the data frame object as a comma-separated values file having a .csv extension.
The official documentation provides the syntax below, We will learn the most commonly used among these in the following sections with an example.
DataFrame.to_csv(path, sep=',', na_rep='', columns=None, header=True, index=True, index_label=None, mode='w', 
encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None, 
doublequote=True, escapechar=None, decimal='.', errors='strict')
Let us look at some of the arguments to save the data-frame as a CSV file
path – The path of the location where the file needs to be saved which end with the name of the file having a .csv extension. If only the name of the file is provided it will be saved in the same location as the script.
sep – Delimiter to be used while saving the file. default is ‘,’.
columns – Names to the columns from the data to write in the file.
header – The name to be given to the columns when writing the file.
index – A boolean value which determines whether the column index to be included or not in the output file.
encoding – String representing the encoding to use in the output file, the default value is ‘utf-8’.
See the code below to save the data frame that we have created above including its column indexes and changing the names of columns.
data1.to_csv('saved_data.csv',
        header=['person_age','product_purchased'],
        sep=',',index=True)
Output:
Country,person_age,product_purchased
Germany,30,No
Spain,38,No
Germany,40,Yes
France,35,Yes
See the code below to save the 10 rows data frame that we have parsed from the employee dataset above but using whitespace as the separator.
import pandas as pd
url = "https://raw.githubusercontent.com/kunalgupta2616/datasets/master/employees.csv"
data2 = pd.read_csv(url,nrows=5,parse_dates=[2])
data2.to_csv('modified_emp_data.csv',sep=' ',index=False)
Output:
"First Name" Gender "Start Date" "Last Login Time" Salary "Bonus %" "Senior Management" Team
Douglas Male 1993-08-06 "12:42 PM" 97308 6.945 True Marketing
Thomas Male 1996-03-31 "6:53 AM" 61933 4.17 True 
Maria Female 1993-04-23 "11:17 AM" 130590 11.857999999999999 False Finance
Jerry Male 2005-03-04 "1:00 PM" 138705 9.34 True Finance
Larry Male 1998-01-24 "4:47 PM" 101004 1.389 True "Client Services"
For convenience output file is uploaded at GitHub whose raw file link – modified_emp_data.csv
So we learned about how we can read a CSV file and save a data frame as a CSV file along with customisations.
What is Python NumPy Library
Read CSV file in Pandas
Happy Learning 🙂

Pandas read_csv – Read CSV file in Pandas and prepare Dataframe
How to Convert Python List Of Objects to CSV File
How to Read CSV File in Python
Java – How to read CSV file and Map to Java Object
How to check whether a file exists python ?
How to read a text file in Python ?
How to Delete a File or Directory in Python
Python – How to create Zip File in Python ?
Java How to create Jar File ?
PHP File Handling fopen fread and fclose  Example
Python – Selenium Download a File in Headless Mode
How to write (PHP fwrite) a file in PHP
How to get Words Count in Python from a File
Spring Boot Batch Example Csv to Database
How to read JSON file in Python ?

Pandas read_csv – Read CSV file in Pandas and prepare Dataframe
How to Convert Python List Of Objects to CSV File
How to Read CSV File in Python
Java – How to read CSV file and Map to Java Object
How to check whether a file exists python ?
How to read a text file in Python ?
How to Delete a File or Directory in Python
Python – How to create Zip File in Python ?
Java How to create Jar File ?
PHP File Handling fopen fread and fclose  Example
Python – Selenium Download a File in Headless Mode
How to write (PHP fwrite) a file in PHP
How to get Words Count in Python from a File
Spring Boot Batch Example Csv to Database
How to read JSON file in Python ?
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list