- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Create a subset by choosing specific values from columns based on indexes
To create a subset by choosing specific values from columns based on indexes, use the iloc() method. Let us first import the pandas library
import pandas as pd
Create a Pandas DataFrame with Product records. We have 3 columns in it
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Creating a subset with 2 columns and 1st 2 rows using iloc(
print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2]
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:\n",dataFrame['Product'] # creating a subset with 2 columns and 1st 2 rows using iloc() print"\nDisplaying a subset using iloc() = \n",dataFrame.iloc[0:2, 0:2]
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: 0 SmartTV 1 ChromeCast 2 Speaker 3 Earphone Name: Product, dtype: object Displaying a subset using iloc() = Closing_Stock Opening_Stock 0 200 300 1 500 700
Advertisements