Python write to csv column

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.

Frequently Asked:

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.

Читайте также:  Integer parseint java try

Summary

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

Источник

Write List to CSV Columns in Python

Write List to CSV Columns in Python

  1. Import the csv Library in Python
  2. Zip All Lists in Python
  3. Add Elements to Columns in Python

This tutorial demonstrates how to write a list to a CSV column in Python.

We will first create a sample CSV file in which we will add our list by the name Sample.csv in a folder. In our case, we create the CSV file in the same location as our Python file.

Import the csv Library in Python

We import the csv library to work on the CSV file.

We will now create 5 sample lists to be added to the CSV file. We create them in the following way.

l1 = ['a', 'b', 'c', 'd', 'e'] l2 = ['f', 'g', 'i', 'j','k'] l3 = ['l', 'm', 'n', 'o', 'p'] l4 = ['q', 'r', 's', 't','u'] l5 = ['v', 'w', 'x', 'y', 'z'] 

Zip All Lists in Python

We will now zip our 5 lists using the zip() function and change them to rows.

The above code will zip our 5 lists.

Add Elements to Columns in Python

We will now open our CSV using the open() function and make our CSV file write-ready by using csv.writer() function.

We write our list elements to our CSV file by taking individual elements and adding them into a column using the writerow() function. We run the below code to add list elements into the columns.

with open('Sample.csv', "w") as s:  w = csv.writer(s)  for row in r:  w.writerow(row) 

The above will result in the following output.

Input image of list into csv file

We can see that the list elements have been successfully added to the columns in our CSV file.

Thus using the above method, we can successfully write lists to a CSV column in Python.

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

Related Article — Python List

Related Article — Python CSV

Copyright © 2023. All right reserved

Источник

Add column to csv python – Python: Add a Column to an Existing CSV File

Python Add a Column to an Existing CSV File

Add column to csv python: In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

Читайте также:  Python list append в начало

We also include these for beginners:

  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Python csv write to specific row and column
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Python add a column to an existing csv file
  • Python add a new column to csv
  • Python add csv column to list
  • Python pandas append column to csv
  • Add a line to a csv file python

Original CSV file content

Method 1-Add a column with the same values to an existing CSV file

Python add column to csv: In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer from csv import reader default_text = 'New column' # Open the input_file in read mode and output_file in write mode with open('example1.csv', 'r') as read_obj, \ open('output_1.csv', 'w', newline='') as write_obj: # Create a csv.reader object from the input file object csv_reader = reader(read_obj) # Create a csv.writer object from the output file object csv_writer = writer(write_obj) # Read each row of the input csv file as list for row in csv_reader: # Append the default text in the row / list row.append(default_text) # Add the updated row / list to the output file csv_writer.writerow(row) output_data=pd.read_csv('output_1.csv') output_data.head()

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

Method 2-Add a column to an existing CSV file, based on values from other columns

How to add a new column to a csv file using python: In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer from csv import reader def add_column_in_csv(input_file, output_file, transform_row): """ Append a column in existing csv using csv.reader / csv.writer classes""" # Open the input_file in read mode and output_file in write mode with open(input_file, 'r') as read_obj, \ open(output_file, 'w', newline='') as write_obj: # Create a csv.reader object from the input file object csv_reader = reader(read_obj) # Create a csv.writer object from the output file object csv_writer = writer(write_obj) # Read each row of the input csv file as list for row in csv_reader: # Pass the list / row in the transform function to add column text for this row transform_row(row, csv_reader.line_num) # Write the updated row / list to the output file csv_writer.writerow(row) add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1])) output_data=pd.read_csv('output_2.csv') output_data.head()
total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61
Читайте также:  Java using configuration files

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

Method 3-Add a list as a column to an existing csv file

Python csv write column: In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer from csv import reader def add_column_in_csv(input_file, output_file, transform_row): """ Append a column in existing csv using csv.reader / csv.writer classes""" # Open the input_file in read mode and output_file in write mode with open(input_file, 'r') as read_obj, \ open(output_file, 'w', newline='') as write_obj: # Create a csv.reader object from the input file object csv_reader = reader(read_obj) # Create a csv.writer object from the output file object csv_writer = writer(write_obj) # Read each row of the input csv file as list for row in csv_reader: # Pass the list / row in the transform function to add column text for this row transform_row(row, csv_reader.line_num) # Write the updated row / list to the output file csv_writer.writerow(row) l=[] l.append("New Column") rows = len(data.axes[0]) for i in range(rows): val=i+1 l.append(val) add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1])) output_data=pd.read_csv('output_3.csv') output_data.head()
total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Test yourself:

  1. Write to a specific column in csv python pandas?
  2. Write to specific column csv python?
  3. How do i add a column to an existing csv file in python?
  4. How to add column in existing csv file using python?

Источник

Оцените статью