0

These are the questions I have:

  1. Syntatically speaking, what are loc and iloc in the pandas library? are they functions? methods? what are their specific classifications?

  2. Why do we use [] when using them?

  3. What do they do and what are they used for?

Sorry for the vagueness lack of clarity in the questions, and also, Thanks!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • What research have you done? There are a bunch of existing questions about `loc` and `iloc`, as well as the Pandas documentation. – wjandrea Jan 08 '22 at 03:52
  • Docs: [Different choices for indexing](https://pandas.pydata.org/docs/user_guide/indexing.html#different-choices-for-indexing), [`pandas.DataFrame.loc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html), [`pandas.DataFrame.iloc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html) – wjandrea Jan 08 '22 at 03:57
  • Related: [Why/How does Pandas use square brackets with .loc and .iloc?](/q/46176656/4518341), [Is loc\[ \] a function in Pandas](/q/66043313/4518341), [How are iloc and loc different?](/q/31593201/4518341) – wjandrea Jan 08 '22 at 03:58
  • Syntactically, they're just attributes, but that isn't very helpful – wjandrea Jan 08 '22 at 04:14

1 Answers1

0

Both LOC and ILOC are methods as they're associated with the Pandas module.

To access values from rows and columns within a Dataframe, both LOC and ILOC are used. One can use these methods to filter and modify values within DF.

LOC - loc() is a label-based data selecting method which means that we have to pass the name of the row or column which we want to select. This method includes the last element of the range passed in it, unlike iloc().

ILOC - iloc() is an indexed-based selecting method which means that we have to pass integer index in the method to select a specific row/column. This method does not include the last element of the range passed in it unlike loc()

Example:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(10,100, (5, 4)), columns = list("ABCD"))

df.loc[1:3, "A":"C"]

before the comma, the colon takes row selections and after the comma, the colon takes column selections, here we've to specify the labels of the rows as well as the columns

df.iloc[1:3, 1:3] 

before the comma, the colon takes row selections and after a comma, the colon takes column selections, here we've to specify the index positions of the rows as well as the columns

csmaster
  • 579
  • 4
  • 14