Writing Data

pandas can also write data to a variety of file formats, including CSV, Excel, and SQL databases. The following code cell writes the elections dataset to a CSV file named elections.csv.



To write a DataFrame to a CSV file, use the df.to_csv() function. The first input to df.to_csv() is the filename or filepath that you want to write to.

pd.to_csv('elections_new.csv')

Other important parameters of the df.to_csv() function are:

  1. sep: (default: sep=',') specifies the separator used to separate columns. Default is , which means the columns are separated by a comma.

  2. header: (default: header=True) specifies whether to write the header row. Default is True which means the header row is written. If you don’t want to write the header row, then header=False should be used.

  3. index: (default: index=True) specifies whether to write the index column. Default is True which means the index column is written. If you don’t want to write the index column, then index=False should be used. data.to_csv(‘elections.csv’)