O'Reilly logo

Learning pandas by Michael Heydt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required