Selecting items by row indexes and column labels
In the following section, we will see how to select items by indexes and column labels.
Getting ready
Run the following code to load NumPy, and pandas, and to initialize a DataFrame
object:
import numpy as np import pandas as pd df1 = pd.DataFrame([['Pen', 24, 2.39], ['Eraser', 32, 1.29], ['Sharpener', 12, 10.39], ['Pencil', 42, 0.59 ]], index=[100024, 201024, 202034, 101122], columns = ['item', 'inventory', 'unit_price'])
How to do it...
Run the following code, which demonstrates different ways to select data from a DataFrame
:
col = df['item'] cols = df[['item', 'inventory']] rows = df[2:4] row_data = df.loc[201024] df1 = df.loc[201024:,['item','unit_price']]
The data selected in each of the commands is displayed as follows:
col
:
100024 Pen 201024 Eraser 202034 Sharpener 101122 Pencil
cols
:
item inventory 100024 ...