- pandas.DataFrame.rename#
- Как переименовать индекс в Pandas DataFrame
- Пример: индекс переименования в Pandas DataFrame
- Дополнительные ресурсы
- pandas.Index.rename#
- Pandas Rename Index: How to Rename a Pandas Dataframe Index
- Loading a Sample Dataframe
- How to Rename a Pandas Dataframe Index
- How to Rename a Pandas Multi-Index
- How to Remove a Pandas Index Name
- Conclusion
- How to Rename Index in Pandas DataFrame
- Step 1: Check index/axis name in Pandas
- Step 2: Pandas rename index name — .rename_axis()
- Step 3: Rename Pandas index with df.index.names
- Step 4: Pandas rename index name -df.index.rename()
- Step 5: Get Pandax index level by name
- Step 6: Pandas rename index column
- Resources
pandas.DataFrame.rename#
Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.
Parameters mapper dict-like or function
Dict-like or function transformations to apply to that axis’ values. Use either mapper and axis to specify the axis to target with mapper , or index and columns .
index dict-like or function
Alternative to specifying axis ( mapper, axis=0 is equivalent to index=mapper ).
columns dict-like or function
Alternative to specifying axis ( mapper, axis=1 is equivalent to columns=mapper ).
Axis to target with mapper . Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’.
copy bool, default True
Also copy underlying data.
inplace bool, default False
Whether to modify the DataFrame rather than creating a new one. If True then value of copy is ignored.
level int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.
errors , default ‘ignore’
If ‘raise’, raise a KeyError when a dict-like mapper , index , or columns contains labels that are not present in the Index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored.
Returns DataFrame or None
DataFrame with the renamed axis labels or None if inplace=True .
If any of the labels is not found in the selected axis and “errors=’raise’”.
DataFrame.rename supports two calling conventions
We highly recommend using keyword arguments to clarify your intent.
Rename columns using a mapping:
>>> df = pd.DataFrame("A": [1, 2, 3], "B": [4, 5, 6]>) >>> df.rename(columns="A": "a", "B": "c">) a c 0 1 4 1 2 5 2 3 6
Rename index using a mapping:
>>> df.rename(index=0: "x", 1: "y", 2: "z">) A B x 1 4 y 2 5 z 3 6
Cast index labels to a different type:
>>> df.index RangeIndex(start=0, stop=3, step=1) >>> df.rename(index=str).index Index(['0', '1', '2'], dtype='object')
>>> df.rename(columns="A": "a", "B": "b", "C": "c">, errors="raise") Traceback (most recent call last): KeyError: ['C'] not found in axis
Using axis-style parameters:
>>> df.rename(str.lower, axis='columns') a b 0 1 4 1 2 5 2 3 6
>>> df.rename(1: 2, 2: 4>, axis='index') A B 0 1 4 2 2 5 4 3 6
Как переименовать индекс в Pandas DataFrame
Вы можете использовать следующий синтаксис для переименования столбца индекса кадра данных pandas:
df.index.rename('new_index_name', inplace= True )
В следующем примере показано, как использовать этот синтаксис на практике.
Пример: индекс переименования в Pandas DataFrame
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
В настоящее время DataFrame не имеет имени индекса:
#display index name print(df.index.name ) None
Мы можем использовать df.index.rename() для переименования индекса:
#rename index df.index.rename('new_index', inplace= True ) #view updated DataFrame df points assists rebounds new_index 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
Обратите внимание, что inplace=True указывает pandas сохранить все исходные свойства DataFrame.
Мы можем убедиться, что DataFrame теперь имеет имя индекса:
#display index name print(df.index.name ) new_index
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:
pandas.Index.rename#
Able to set new names without level. Defaults to returning new index. Length of names must match number of levels in MultiIndex.
Parameters name label or list of labels
inplace bool, default False
Modifies the object directly, instead of creating a new Index or MultiIndex.
The same type as the caller or None if inplace=True .
Able to set new names partially and by level.
>>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score') >>> idx.rename('grade') Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')
>>> idx = pd.MultiIndex.from_product([['python', 'cobra'], . [2018, 2019]], . names=['kind', 'year']) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['kind', 'year']) >>> idx.rename(['species', 'year']) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['species', 'year']) >>> idx.rename('species') Traceback (most recent call last): TypeError: Must pass list-like as `names`.
Pandas Rename Index: How to Rename a Pandas Dataframe Index
In this tutorial, you’ll learn how to use Pandas to rename an index, including how to rename a Pandas dataframe index and a Pandas multi-index dataframe. By renaming a Pandas dataframe index, you’re changing the name of the index column.
The Quick Answer: Use df.index.names
Loading a Sample Dataframe
If you want to follow along with the dataframe, feel free to copy and paste the code below into your code editor of choice. If you have your own dataframe you’re using, you may need to adjust some of the code to follow along.
import pandas as pd df = pd.DataFrame.from_dict( < 'Year': [2018, 2019, 2020, 2021], 'Carl': [1000, 2300, 1900, 3400], 'Jane': [1500, 1700, 1300, 800], 'Melissa': [800, 2300, None, 2300] >).set_index('Year') print(df)
This returns the following dataframe:
Carl Jane Melissa Year 2018 1000 1500 800.0 2019 2300 1700 2300.0 2020 1900 1300 NaN 2021 3400 800 2300.0
Let’s get started on renaming a Pandas dataframe index.
How to Rename a Pandas Dataframe Index
Pandas makes it very easy to rename a dataframe index. Before we dive into that, let’s see how we can access a dataframe index’s name.
We can access the dataframe index’s name by using the df.index.name attribute.
Let’s see what that looks like in Python:
# Get a dataframe index name index_name = df.index.names print(index_name) # Returns: ['Year']
We can see that when we use the .names attribute, that a list of all the index names are returned. Similarly, we could use the .name attribute if we know we only have one index. This would return just the value, rather than a list of values.
So, to rename a Pandas dataframe index, we can simply assign something to that attribute. This can be particularly helpful when renaming a Pandas dataframe index after using a Pandas pivot table function.
Want to learn more? Check out my in-depth guide to Pandas pivot tables in my post here.
Let’s see how this looks in Python, by renaming our index to ‘Time Period’ :
df.index.names = ['Time Period'] print(df)
This returns the new dataframe below, with a renamed index:
Carl Jane Melissa Time Period 2018 1000 1500 800.0 2019 2300 1700 2300.0 2020 1900 1300 NaN 2021 3400 800 2300.0
Now, make note of the fact that we passed in a list of names. If we had used the .name attribute, we could have simply passed in the string ‘Time Period’ .
Now that you know how to rename a Pandas dataframe index, let’s see how to rename a multi-index dataframe.
How to Rename a Pandas Multi-Index
Working with Pandas multi-index dataframes can be a tricky thing – but renaming their indices doesn’t need to be.
This actually works in the same way as the method above. We directly assign a list of values to the .names attribute.
Let’s load a multi-index dataframe and see how we can rename its index names:
import pandas as pd df = pd.DataFrame.from_dict( < 'Year': [2018, 2019, 2020, 2021], 'Carl': [1000, 2300, 1900, 3400], 'Jane': [1500, 1700, 1300, 800], 'Melissa': [800, 2300, None, 2300] >).set_index(['Year', 'Carl']) print(df)
This returns the following Pandas dataframe:
Jane Melissa Year Carl 2018 1000 1500 800.0 2019 2300 1700 2300.0 2020 1900 1300 NaN 2021 3400 800 2300.0
Now, when we want to see the names of the multi-index dataframe, we can call the .names attribute again:
print(df.index.names) # Returns: ['Year', 'Carl']
Similarly, we can rename a multi-index dataframe indices by assigning a list to the .names attribute. Let’s say we want to name them: ‘Time Period’ and ‘Average Sales’:
df.index.names = ['Time Period', 'Average Sales'] print(df)
This returns the following dataframe:
Jane Melissa Time Period Average Sales 2018 1000 1500 800.0 2019 2300 1700 2300.0 2020 1900 1300 NaN 2021 3400 800 2300.0
In this section, you learned how to rename the indices of a multi-index dataframe. In the final section, you’ll learn how to remove a Pandas dataframe index entirely.
How to Remove a Pandas Index Name
There may be many times when you don’t want your Pandas dataframe’s index to be called anything. This can be particularly useful after you create a Pandas pivot table, since the index names can often be misleading.
To remove a Pandas dataframe index name, we can simply assign it an empty string » or the value of None . Lets see how we can do this with our original dataframe:
import pandas as pd df = pd.DataFrame.from_dict( < 'Year': [2018, 2019, 2020, 2021], 'Carl': [1000, 2300, 1900, 3400], 'Jane': [1500, 1700, 1300, 800], 'Melissa': [800, 2300, None, 2300] >).set_index('Year') df.index.name = None print(df)
This returns a dataframe without a named index, as shown below:
Carl Jane Melissa 2018 1000 1500 800.0 2019 2300 1700 2300.0 2020 1900 1300 NaN 2021 3400 800 2300.0
In this section, you learned how to remove a Pandas dataframe index name.
Conclusion
In this post, you learned how to rename a Pandas dataframe index, using the .name and .names attributes. You learned how to rename the index on a single-index dataframe as well as a multi-index dataframe. Finally, you learned how to remove a Pandas index name.
To learn more about the Pandas dataframe index.name attribute, check out the official documentation here.
How to Rename Index in Pandas DataFrame
There are two approaches to rename index/columns in Pandas DataFrame:
(1) Set new index name by df.index.names
(2) Rename index name with rename_axis
(3) Rename column name with rename_axis
df.rename_axis('col_index', axis=1)
In the rest of this article you can find a few practical examples on index renaming for columns and rows.
To start, let’s create a sample DataFrame with 2 columns:
import pandas as pd df = pd.DataFrame(< 'name':['Softhints', 'DataScientyst'], 'url':['https://www.softhints.com', 'https://datascientyst.com'] >)
Step 1: Check index/axis name in Pandas
First let’s check if there’s an index name by:
The index don’t have any name set:
RangeIndex(start=0, stop=2, step=1)
The same is for the columns:
Index(['name', 'url'], dtype='object')
Step 2: Pandas rename index name — .rename_axis()
Pandas offers a method called .rename_axis(‘companies’) which is intended for index renaming.
To rename index with rename_axis in Pandas DataFrame use:
name | url | |
---|---|---|
org_id | ||
0 | Softhints | https://www.softhints.com |
1 | DataScientyst | https://datascientyst.com |
You can notice the index name org_id which is on the top of the index.
Let’s check the index name by df.index :
RangeIndex(start=0, stop=2, step=1, name='org_id')
It’s visible by name=’org_id’
For changing column index name you can use — axis=1 :
df = df.rename_axis('company_data', axis=1)
company_data | name | url |
---|---|---|
org_id | ||
0 | Softhints | https://www.softhints.com |
1 | DataScientyst | https://datascientyst.com |
and for columns we have name added to the index:
Index(['name', 'url'], dtype='object', name='company_data')
Step 3: Rename Pandas index with df.index.names
Another option to rename any axis is to use the names attribute: df.index.names .
So to rename the index name is by:
df.columns.names = ['company_data']
The result is exactly the same as in the previous step.
Step 4: Pandas rename index name -df.index.rename()
Pandas offers method index.rename which can be used to change the index name for both rows and/or columns:
df.index = df.index.rename('test')
RangeIndex(start=0, stop=2, step=1, name='test')
Step 5: Get Pandax index level by name
Finally let’s cover how index can be extracted by it’s name:
df.index.get_level_values('test')
This is useful for hierarchical indexes.
So to access data by index name use:
df.loc[df.index.get_level_values('test')]
Step 6: Pandas rename index column
To rename column index in Pandas we need to pass parameter axis=1 to method rename_axis() :
df.rename_axis('col_index', axis=1)