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
Using Python and the CSV module, we can manipulate the CSV files as follows:
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>
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!