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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.