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 df[:2] Out[48]: Sector Price ...
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.