Home »
Python »
Python Programs
How to write specific columns of a DataFrame to a CSV?
Given a pandas dataframe, we have to write specific columns of a DataFrame to a CSV.
Submitted by Pranit Sharma, on October 04, 2022
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
What are CSV files?
CSV files or Comma Separated Values files are plain text files but the format of CSV files is tabular. As the name suggests, in a CSV file, each specific value inside the CSV file is generally separated by a comma. The first line identifies the name of a data column. The further subsequent lines identify the values in rows.
col_1_value, col_2_value , col_3_value
Row1_value1 , row_1_value2 , row_1_value3
Row1_value1 , row_1_value2 , row_1_value3
Here, the separator character (,) is called the delimiter. There are some more popular delimiters. E.g.: tab(\t), colon (:), semi-colon (;) etc.
Problem statement
Given a pandas dataframe, we have to write specific columns of a DataFrame to a CSV.
Writing specific columns of a DataFrame to a CSV
We will use pandas.DataFrame.to_csv() method to write DataFrame into csv file. It takes an argument in the form of a DataFrame name which has to be written in a CSV file. But to write specific columns of a DataFrame to a CSV, we will first create a list of those specific columns which we want to be part of the CSV file and then we will create this CSV file.
Let us understand with the help of an example,
Python program to write specific columns of a DataFrame to a CSV
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {
'A':[1,2,3,4,5,6],
'B':[2,3,4,5,6,7],
'C':[3,4,5,6,7,8],
'D':[4,5,6,7,8,9],
'E':[5,6,7,8,9,10]
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display created DataFrame
print("Created DataFrame:\n",df,"\n")
# creating list of columns
l = ['A','B','C','D']
# Writing specific columns in csv file
df.to_csv('D:/Includehelp/output.csv', columns = l)
# Dislay a msg
print("CSV file created")
Output
The output of the above program is:
Python Pandas Programs »