What is the difference between using squared brackets or dot to access a column?

前端 未结 3 873
感情败类
感情败类 2020-11-22 06:55

In both the bellow cases:

import pandas

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

print(df[\'col2\'])
print(df.col2)
         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 07:28

    The "dot notation", i.e. df.col2 is the attribute access that's exposed as a convenience.

    You may access an index on a Series, column on a DataFrame, and an item on a Panel directly as an attribute:

    df['col2'] does the same: it returns a pd.Series of the column.

    A few caveats about attribute access:

    • you cannot add a column (df.new_col = x won't work, worse: it will silently actually create a new attribute rather than a column - think monkey-patching here)
    • it won't work if you have spaces in the column name or if the column name is an integer.

提交回复
热议问题