
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Subset DataFrame Using Indexing Operator in Python Pandas
The indexing operator is the square brackets for creating a subset dataframe. Let us first create a Pandas DataFrame. We have 3 columns in the DataFrame
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Creating a subset with a single column
dataFrame[['Product']]
Creating a subset with multiple columns
dataFrame[['Opening_Stock','Closing_Stock']]
Example
Following is the complete code
import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...\n",dataFrame print"\nDisplaying a subset using indexing operator:\n",dataFrame[['Product']] print"\nDisplaying a subset with multiple columns:\n",dataFrame[['Opening_Stock','Closing_Stock']]
Output
This will produce the following output
DataFrame... Closing_Stock Opening_Stock Product 0 200 300 SmartTV 1 500 700 ChromeCast 2 1000 1200 Speaker 3 900 1500 Earphone Displaying a subset using indexing operator: Product 0 SmartTV 1 ChromeCast 2 Speaker 3 Earphone Displaying a subset with multiple columns: Opening_Stock Closing_Stock 0 300 200 1 700 500 2 1200 1000 3 1500 900
Advertisements