cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
missing-QuestionPost
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Access content in dataframe by loc/iloc or by [ ] [ ]?

AleksandraFrolo
New Contributor III

Hello,

Task: I am trying to understand, what approach is better to access the content in DataFrame.

My piece of code:

print("First approach: ", df["Purchase Address"][0])
 
print("Second approach: ", df.loc[0,"Purchase Address"])

These lines are equal to each other. For me more comfortable to use first version. Is there any recommends in pandas how to access the content?

1 ACCEPTED SOLUTION

Accepted Solutions

-werners-
Esteemed Contributor III
2 REPLIES 2

-werners-
Esteemed Contributor III

Anonymous
Not applicable

@Aleksandra Frolovaโ€‹ :

Both approaches you mentioned are valid ways to access content in a DataFrame in pandas. Let's take a closer look at each approach:

Using brackets []:

df["Purchase Address"][0]

Using loc or iloc:

df.loc[0, "Purchase Address"]

Both approaches have their advantages depending on the specific use case:

  • The bracket notation [] is simpler and more concise, making it suitable for quick access to specific elements or simple slicing operations. It is commonly used when you have a straightforward DataFrame structure or when you want to access a specific column or row quickly.
  • The loc or iloc indexer is more versatile and powerful. It allows you to access elements using label-based indexing (loc) or integer-based indexing (iloc). This is especially useful when you have complex DataFrame structures, customized row and column labels, or when you need more control over your indexing operations.

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group