Python - How to select a subset of a Pandas DataFrame


Let’s say the following are the contents of our CSV file opened in Microsoft Excel −

At first, load data from a CSV file into a Pandas DataFrame −

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")

To select a subset, use the square brackets. Mention the column in the brackets and fetch single column from the entire dataset −

dataFrame['Car']

Example

Following is the code −

import pandas as pd

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")
print("\nReading the CSV file...\n",dataFrame)

# displaying only a single column
res1 = dataFrame['Car'];
# displaying only a subset
print("\nDisplaying only one column Car : \n",res1)

# displaying two columns
res2 = dataFrame[['Car','Units']];
# displaying another subset
print("\nDisplaying two columns : \n",res2)

Output

This will produce the following output −

Reading the CSV file...
       Car   Reg_Price   Units
0      BMW        2500     100
1    Lexus        3500      80
2     Audi        2500     120
3   Jaguar        2000      70
4  Mustang        2500     110

Displaying only one column Car :
0      BMW
1    Lexus
2     Audi
3   Jaguar
4  Mustang
Name: Car, dtype: object

Displaying two columns :
       Car   Units
0      BMW     100
1    Lexus      80
2     Audi     120
3   Jaguar      70
4  Mustang     110

Updated on: 29-Sep-2021

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements