如何使用 CSV 模組從 CSV 檔案中的特定列中提取資料?

Patricia Arquette
發布: 2024-11-15 05:23:02
原創
906 人瀏覽過

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
登入後複製

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
登入後複製

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

以上是如何使用 CSV 模組從 CSV 檔案中的特定列中提取資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板