Home > Backend Development > Python Tutorial > How to Add a New Column Derived from Existing Data to a CSV File Using Python?

How to Add a New Column Derived from Existing Data to a CSV File Using Python?

DDD
Release: 2024-10-21 21:00:30
Original
302 people have browsed it

How to Add a New Column Derived from Existing Data to a CSV File Using Python?

Modifying CSV Files: Adding a New Column

Problem Statement

Given a CSV file with columns named 'Name' and 'Code', we aim to add a new column called 'Berry' with values derived from the 'Name' column. The desired output should resemble:

Name        Code    Berry
blackberry  1   blackberry
wineberry   2   wineberry
rasberry    1   rasberry
blueberry   1   blueberry
mulberry    2   mulberry
Copy after login

Proposed Solution

Using Python and the CSV module, we can manipulate the CSV files as follows:

  1. Open the input CSV file for reading and the output CSV file for writing.
  2. Iterate over each row in the input file using csv.reader.
  3. For each row, append the desired value for the new 'Berry' column.
  4. Write the modified rows to the output file using csv.writer.

Here's an example script:

<code class="python">import csv

with open('input.csv', 'r') as input_file, open('output.csv', 'w') as output_file:
    reader = csv.reader(input_file)
    writer = csv.writer(output_file)

    # Read the header row and add the new column
    header = next(reader)
    header.append('Berry')
    writer.writerow(header)

    # Iterate over the remaining rows and modify them
    for row in reader:
        row.append(row[0])    # Set the 'Berry' column to the 'Name' column
        writer.writerow(row)</code>
Copy after login

Notable Considerations

  • The csv.reader and csv.writer functions handle reading and writing rows from and to the CSV files, respectively.
  • The open function with with statement ensures proper file handling and cleanup.
  • The next(reader) function reads the first row (header) and advances the iterator, which is necessary for adding the new column to the header.
  • In Python 3, the iterator obtained from csv.reader yields tuples, so we must convert them to lists before modifying and writing them.

By following these steps, we can successfully add a new column to our CSV files, enhancing their data representation.

The above is the detailed content of How to Add a New Column Derived from Existing Data to a CSV File Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template