Modifying the structure and content of DataFrame

The structure and content of a DataFrame can be mutated in several ways. Rows and columns can be added and removed, and data within either can be modified to take on new values. Additionally, columns, as well as index labels, can also be renamed. Each of these will be described in the following sections.

Renaming columns

A column can be renamed using the .rename() method of the DataFrame. The Book Value column is inconvenient since it has a space, so we will rename it to BookValue:

In [48]:
   # rename the Book Value column to not have a space
   # this returns a copy with the column renamed
   df = sp500.rename(columns=
                     {'Book Value': 'BookValue'})
   # print first 2 rows

 Sector Price ...

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.