- 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 – Create a Subset of columns using filter()
To create a subset of columns, we can use filter(). Through this, we can filter column values with similar pattern using like operator. At first, let us create a DataFrame with 3 columns −
dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Now, let us create a subset with multiple columns −
dataFrame[['Opening_Stock','Closing_Stock']]
Create a subset with similarly patterned names −
dataFrame.filter(like='Open')
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']] print"\nDisplaying a subset with similarly patterned names:\n",dataFrame.filter(like='Open')
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 Displaying a subset with similarly patterned names: Opening_Stock 0 300 1 700 2 1200 3 1500
Advertisements