Selecting columns of a DataFrame

Selecting the data in specific columns of a DataFrame is performed by using the [] operator. This can be passed either as a single object, or a list of objects. These objects are then used to lookup columns either by zero-based location, or by matching the objects to the values in the columns index.

Passing a single integer, or a list of integers, to [] will have the DataFrame object attempt to perform a location based lookup of the columns. The following code retrieves the data in the second and third columns:

In [22]:
   # get first and second columns (1 and 2) by location
   sp500[[1, 2]].head()

Out[22]:
            Price  Book Value
   Symbol                    
   MMM     141.14      26.668
   ABT      39.60      15.573
   ABBV     53.95       2.954
   ACN      79.79       8.326
 ACE 102.91 ...

Get Learning pandas now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.