Python - Select multiple columns from a Pandas dataframe

PythonServer Side ProgrammingProgramming

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 multiple column records, use the square brackets. Mention the columns in the brackets and fetch multiple columns from the entire dataset −

dataFrame[['Reg_Price','Units']]

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 two columns
res = dataFrame[['Reg_Price','Units']];
print("\nDisplaying two columns : \n",res)

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 two columns :
    Reg_Price   Units
0        2500     100
1        3500      80
2        2500     120
3        2000      70
4        2500     110
raja
Published on 29-Sep-2021 11:41:31
Advertisements