Write a CSV file by Column in Python

In this article, we will discuss how to write columns in a csv file in Python.

Table Of Contents

Introduction

Suppose we have four lists,

# Lists containing column values for csv file
column1 = ['Ritika', 'Mark', 'Suse', 'Shaun']
column2 = [27, 28, 29, 30]
column3 = ['Delhi', 'Sydney', 'Las Vegas', 'London']
column4 = ['India', 'Australia', 'USA', 'UK']

Now we want to create a csv file, and use each of the above list as a column in csv file. The contents of csv file should be like this,

Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

There are different ways to write a csv file column by column. Let’s discuss them one by one.

Write a CSV file by Column using Pandas

Create a dictionary of key-value pairs. In each pair, key is the column name and value field contains a list i.e. column values. Then use this dictionary to create a Pandas DataFrame object. After that, set the column with label “Name” as the index column of DataFrame. Then call the to_csv() function of DataFrame to store the data in csv file. Let’s see an example,

import pandas as pd

# Lists containing column values for csv file
column1 = ['Ritika', 'Mark', 'Suse', 'Shaun']
column2 = [27, 28, 29, 30]
column3 = ['Delhi', 'Sydney', 'Las Vegas', 'London']
column4 = ['India', 'Australia', 'USA', 'UK']

# Create a dictionary where each pair contains
# a column name and column contents for csv file and 
mapping = { 'Name'    : column1,
            'Age'     : column2,
            'City'    : column3,
            'Country' : column4}

# Create a DataFrame from mapping
df = pd.DataFrame(mapping)

# Set column 'Name' as the indesx
df = df.set_index('Name')

# Create csv file the dataFrame
df.to_csv('employees.csv')

It will create a csv file “employees.csv”, with the following content,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

If you don’t want the header, then call the to_csv() function with header as None. For example,

# Create csv file from dataFrame without header
df.to_csv('employees2.csv', header=None)

It will create a csv file “employees2.csv”, but without the header row. Contents of the csv file will be,

Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

Write a CSV file by Column using CSV Writer

Open file in write mode, and get a file object. Then pass this file object to writer() function of csv module to get the csv_writer object. Then zip all the lists together to create a zipped object. Iterate over this zipped object, and each ith element of this zipped object will be a tuple containing the ith values from the zipped lists. Add this tuple as row in the csv using writerow() function of csv writer object. This way, we can write a csv file by using lists as columns. For example,

import csv

# Lists containing column values for csv file
column1 = ['Ritika', 'Mark', 'Suse', 'Shaun']
column2 = [27, 28, 29, 30]
column3 = ['Delhi', 'Sydney', 'Las Vegas', 'London']
column4 = ['India', 'Australia', 'USA', 'UK']

# Open csv file for writing
with open('employees3.csv', 'w') as fileObj:
    # Create a CSV Writer object
    writerObj = csv.writer(fileObj)
    # Zip all the column lists and iterate over zipped objects
    for row in zip(column1, column2, column3, column4):
        # Add a zipped object as a row in the csv file
        writerObj.writerow(row)

It will create a csv file “employees3.csv”, with the following content,

Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

We created a csv file from four lists. Each list represents a column of the csv file.

Summary

We learned how to write a csv file column by column in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top