Python Pandas - Subset DataFrame by Column Name


To create a subset of DataFrame by column name, use the square brackets. Use the DataFrame with square brackets (indexing operator) and the specific column name like this −

dataFrame[‘column_name’]

At first, import the required library with alias −

import pandas as pd

Create a Pandas DataFrame with Product records −

dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],
"Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})

Let us fetch a subset i.e. we are fetching only Product column records

dataFrame['Product']

Example

Following is the 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']

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

Updated on: 14-Sep-2021

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements