Renaming Pandas DataFrame Index
This question pertains to renaming both the index and column names of a DataFrame. While the df.rename() method can modify column names, it faces difficulty when it comes to renaming the index.
The key to understanding this issue lies in the distinction between index values and index names. The df.rename() method operates on index values, while the desired operation involves modifying index names.
To successfully rename index names, utilize the following syntax:
<code class="python">df.index.names = ['NewName']</code>
For a more comprehensive understanding, consider the following examples:
<code class="python">df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=list('ABC')) df.index.names = ['Date']</code>
<code class="python">df1 = df.set_index('A') df1.rename(index={1: 'a'})</code>
<code class="python">df1.rename(columns={'B': 'BB'})</code>
It's crucial to note that index names are similar in concept to column names, as both are instances of the same object type (Index or MultiIndex). This equivalence allows for interchangeability between columns and index via transpose.
The above is the detailed content of How to Rename Pandas DataFrame Index Names?. For more information, please follow other related articles on the PHP Chinese website!