Read CSV Columns in Pandas

Use the read_csv function in pandas to read a csv file, and specify the columns parameter to select the columns that need to be read.

Here is the sample code:

import pandas as pd

# 读取整个csv文件,不指定列
df = pd.read_csv('data.csv')

# 读取指定列
selected_columns = ['column1', 'column2', 'column3']
df_selected = pd.read_csv('data.csv', usecols=selected_columns)

In the second example, the ‘usecols’ parameter is used to specify the columns that need to be read by passing the column names as a list to this parameter.

It is important to note that if the column names in the CSV file to be read do not completely match the column names in selected_columns, a KeyError error may occur. Therefore, ensuring the accuracy of the column names is crucial.

bannerAds