Home > Backend Development > Python Tutorial > Pandas Column Access: Dot Notation vs. Square Brackets – When to Use Which?

Pandas Column Access: Dot Notation vs. Square Brackets – When to Use Which?

Susan Sarandon
Release: 2024-11-19 02:31:03
Original
337 people have browsed it

Pandas Column Access: Dot Notation vs. Square Brackets – When to Use Which?

Attribute Access: Dot vs. Square Brackets in Pandas

In Pandas, accessing a column is possible both through attribute access (dot notation) and square brackets. While both approaches yield the same result, there are subtle differences to consider.

Consider the following example:

import pandas

d = {'col1': 2, 'col2': 2.5}
df = pandas.DataFrame(data=d, index=[0])

print(df['col2'])
print(df.col2)
Copy after login

Both methods return the same result:

2.5
Copy after login

Dot Notation: Attribute Access

df.col2 uses the attribute access feature. It directly exposes the attribute corresponding to the column name. This is a convenient shorthand that is functionally equivalent to:

df.__getitem__('col2')
Copy after login

Square Brackets: Column Indexing

df['col2'] uses square bracket indexing. This approach is more flexible and allows for various manipulations beyond attribute access. For instance, you can index multiple columns:

df[['col1', 'col2']]
Copy after login

Caveats of Attribute Access

While attribute access is convenient, it has some limitations:

  • No Column Addition: Attribute access does not permit adding new columns to a DataFrame (e.g., df.new_col = x will not work).
  • Namespaced Column Names: Attribute access fails for columns with spaces or integer names (e.g., df.'col 1' or df.2).

In such scenarios, it is recommended to use square bracket indexing to ensure proper functionality.

The above is the detailed content of Pandas Column Access: Dot Notation vs. Square Brackets – When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template