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
3 REPLIES 3

-werners-
Esteemed Contributor III

Kaniz
Community Manager
Community Manager

Hi @Aleksandra Frolovaโ€‹ , To assist you better, please take a moment to review the answer given by @Werner Stinckensโ€‹ and let me know if it best fits your needs.

Please help us select the best solution by clicking on "Select As Best" if it does.

Your feedback will help us ensure that we are providing the best possible service to you.

Thank you!

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.

Join 100K+ Data Experts: Register Now & Grow with Us!

Excited to expand your horizons with us? Click here to Register and begin your journey to success!

Already a member? Login and join your local regional user group! If there isn’t one near you, fill out this form and we’ll create one for you to join!