DataFrame slicing using loc in Pandas
loc selects data only by labels:
import pandas as pd df = pd.DataFrame({'Age': [30, 20, 22, 40, 32, 28, 39], 'Color': ['Blue', 'Green', 'Red', 'White', 'Gray', 'Black', 'Red'], 'Food': ['Steak', 'Lamb', 'Mango', 'Apple', 'Cheese', 'Melon', 'Beans'], 'Height': [165, 70, 120, 80, 180, 172, 150], 'Score': [4.6, 8.3, 9.0, 3.3, 1.8, 9.5, 2.2], 'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX'] }, index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean', 'Christina', 'Cornelia']) print("\n -- Selecting a single row with .loc with a string -- \n") print(df.loc['Penelope']) print("\n -- Selecting multiple rows with .loc with a list of strings -- \n") print(df.loc[['Cornelia', 'Jane', 'Dean']]) print("\n -- Selecting multiple rows with .loc with slice notation -- \n") print(df.loc['Aaron':'Dean'])
C:\python\pandas examples>pycodestyle --first example12.py C:\python\pandas examples>python example12.py -- Selecting a single row with .loc with a string -- Age 40 Color White Food Apple Height 80 Score 3.3 State AL Name: Penelope, dtype: object -- Selecting multiple rows with .loc with a list of strings -- Age Color Food Height Score State Cornelia 39 Red Beans 150 2.2 TX Jane 30 Blue Steak 165 4.6 NY Dean 32 Gray Cheese 180 1.8 AK -- Selecting multiple rows with .loc with slice notation -- Age Color Food Height Score State Aaron 22 Red Mango 120 9.0 FL Penelope 40 White Apple 80 3.3 AL Dean 32 Gray Cheese 180 1.8 AK C:\python\pandas examples>
2018-10-15T01:46:29+05:30
2018-10-15T01:46:29+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution