logo_learn_stats

Pandas: How you can Worth read_csv with usecols Argument

Posted on
banner 336x280

You’ll virtue the usecols argument inside the read_csv() serve as to learn explicit columns from a CSV document right into a pandas DataFrame.

There are two familiar tactics to virtue this argument:

banner 468x60

Form 1: Worth usecols with Column Names

df = pd.read_csv('my_data.csv', usecols=['this_column', 'that_column'])

Form 2: Worth usecols with Column Positions

df = pd.read_csv('my_data.csv', usecols=[0, 2])

Refer to examples display easy methods to virtue each and every mode in apply with please see CSV document referred to as basketball_data.csv:

Instance 1: Worth usecols with Column Names

We will virtue please see code to import the CSV document and handiest virtue the columns referred to as ‘team’ and ‘rebounds’:

import pandas as pd

#import DataFrame and handiest virtue 'crew' and 'rebounds' columns
df = pd.read_csv('basketball_data.csv', usecols=['team', 'rebounds'])

#view DataFrame
print(df)

   crew  rebounds
0  A     10
1  B     9
2  C     6
3  D     2

Realize that handiest the crew and rebounds columns have been imported since those have been the names of the columns that we specified within the usecols argument.

Instance 2: Worth usecols with Column Positions

We will virtue please see code to import the CSV document and handiest virtue the columns in index positions 0 and a pair of:

import pandas as pd

#import DataFrame and handiest virtue columns in index positions 0 and a pair of
df = pd.read_csv('basketball_data.csv', usecols=[0, 2])

#view DataFrame
print(df)

   crew  rebounds
0  A     10
1  B     9
2  C     6
3  D     2

Realize that handiest the crew and rebounds columns have been imported since those have been the columns in index positions 0 and a pair of, which can be the values that we specified within the usecols argument.

Word: The primary column within the CSV document has an index place of 0.

Extra Sources

Refer to tutorials provide an explanation for easy methods to carry out alternative familiar duties in Python:

Pandas: How you can Skip Rows when Studying CSV Report
Pandas: How you can Learn Excel Information
Pandas: How you can Export DataFrame to Excel

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *