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

Updated on: 14-Sep-2021

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements