Saving my csv output into file using python


I’m new to python and would like to learn data sets, I have following script to load and manipulate my csv file

# import pandas with shortcut 'pd'
import pandas as pd
# read_csv function which is used to read the required CSV file
data = pd.read_csv('data/dummy-data-export-large.csv')
# display
print("Original CSV Data: n")
# pop function which is used in removing or deleting columns from the CSV files
data.pop('Order ID')
data.pop('Product ID')
data.pop('Product Tag')
data.pop('Sales Person')
data.pop('Main Ingredient')
# display
print("nCSV Data after deleting the columns:n")

Rather than printing the data I would like to be able to save into (new) csv file.

Many thanks, T

Being able to save into file

Asked By: napoleon182



You can use the to_csv() method on the DataFrame for writing a CSV to disk:


Check the official documentation to get information about arguments that can be used with that method.

Also, you should not use .pop() if you not want to make further use of the column, as .pop() returns the item after dropping.

To drop columns, better use the drop() method which enables you to drop multiple columns at once and will also be computationally cheaper:

data = data.drop(['Order ID', 'Day', 'Month'], axis=1)


data.drop(['Order ID', 'Day', 'Month'], axis=1, inplace=True)
Answered By: psalt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.