Slicing Only Columns Using .loc[]

cereal.loc[:, 'calories':'fiber']
calories protein fat sodium fiber
0 70 4 1 130 10.0
1 120 3 5 15 2.0
2 70 4 1 260 9.0
... ... ... ... ... ...
74 100 3 1 230 3.0
75 100 3 1 200 3.0
76 110 2 1 200 1.0

77 rows × 5 columns

So Far

  • .loc[] is used to slice columns and rows by label and within an interval.

  • We always specify row indexing first, then columns.

cereal.loc['row name start':'row name end', 'column name start':'column name end']
  • If we aren’t slicing any columns, but we are slicing rows we can shorten that to
df.loc['row name start':'row name end']
  • However, the reverse is not true. If we want all the rows with only specific columns, we specify we want all the row first with just a colon : followed by interval of the columns:
df.loc[:, 'column name start':'column name end']
  • We can read : as “to”.

  • If the indices are labeled with numbers, we do not need “quotations” when calling them. This is only when the labels are using letters.

Let’s apply what we learned!