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)
Both methods return the same result:
2.5
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')
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']]
While attribute access is convenient, it has some limitations:
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!