Home > Backend Development > Python Tutorial > How to Extract Data from Specific Columns in a CSV File with the CSV Module?

How to Extract Data from Specific Columns in a CSV File with the CSV Module?

Patricia Arquette
Release: 2024-11-15 05:23:02
Original
994 people have browsed it

How to Extract Data from Specific Columns in a CSV File with the CSV Module?

Extracting Data from Specific Columns in a CSV File with the CSV Module

In working with CSV files, it is often necessary to extract data from specific columns only. To achieve this using the CSV module, it is important to understand how the library handles data retrieval.

In the provided code sample, the attempt to access specific columns is through row[i] syntax, where i represents the column number. However, the result is not as expected due to an incorrect approach.

The correct method is to include the print statement within the for loop. The following corrected code demonstrates this:

import csv

included_cols = [1, 2, 6, 7]
with open("csv_file.csv") as csvfile:
    reader = csv.reader(csvfile, delimiter=",")
    for row in reader:
        content = list(row[i] for i in included_cols)
        print(content)  # Include the print statement within the loop to display each row
Copy after login

Now, the modified code will print out the values from the desired columns for each row.

However, it's worth mentioning an alternative approach using the pandas library, which simplifies the handling of CSV files. With pandas, you can easily read a CSV file and extract specific columns into variables:

import pandas as pd

df = pd.read_csv("csv_file.csv")
names = df["Name"]  # Use df['column_name'] to extract a specific column into a variable
Copy after login

The pandas library provides a versatile set of tools for working with structured data, making it a recommended choice for handling CSV files effectively.

The above is the detailed content of How to Extract Data from Specific Columns in a CSV File with the CSV Module?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template