The difference between double brace `[[…]]` and single brace `[..]` indexing in Pandas

后端 未结 3 1618
梦如初夏
梦如初夏 2020-12-03 10:53

I\'m confused about the syntax regarding the following line of code:

x_values = dataframe[[\'Brains\']]

The dataframe object consists of 2

3条回答
  •  無奈伤痛
    2020-12-03 11:02

    Other solutions demonstrate the difference between a series and a dataframe. For the Mathematically minded, you may wish to consider the dimensions of your input and output. Here's a summary:

    Object                                Series          DataFrame
    Dimensions (obj.ndim)                      1                  2
    Syntax arg dim                             0                  1
    Syntax                             df['col']        df[['col']]
    Max indexing dim                           1                  2
    Label indexing              df['col'].loc[x]   df.loc[x, 'col']
    Label indexing (scalar)      df['col'].at[x]    df.at[x, 'col']
    Integer indexing           df['col'].iloc[x]  df.iloc[x, 'col']
    Integer indexing (scalar)   df['col'].iat[x]   dfi.at[x, 'col']
    

    When you specify a scalar or list argument to pd.DataFrame.__getitem__, for which [] is syntactic sugar, the dimension of your argument is one less than the dimension of your result. So a scalar (0-dimensional) gives a 1-dimensional series. A list (1-dimensional) gives a 2-dimensional dataframe. This makes sense since the additional dimension is the dataframe index, i.e. rows. This is the case even if your dataframe happens to have no rows.

提交回复
热议问题