- Как переименовать индекс в Pandas DataFrame
- Пример: индекс переименования в Pandas DataFrame
- Дополнительные ресурсы
- Pandas Set Index Name to DataFrame
- 1. Quick Examples of pandas Set Index Name
- 2. Get Index Name From pandas DataFrame
- 3. Assign Column as Index using set_index()
- 4. pandas Set Index Name using rename_axis()
- 5. Using DataFrame.index.rename() get Pandas Index Title/Name
- 6. Add Multiple Index Using DataFrame.set_index()
- 7. Rename Multi Level Index Names Using index.set_names()
- 8. Rename Multiple/All Level of Indexes
- 9. Complete Examples of pandas Set Index Name
- 10. Conclusion
- Related Articles
- Reference
- You may also like reading:
- Get and Set Pandas DataFrame Index Name
- Get the Name of the Index Column of a DataFrame
- Set the Name of the Index Column of a DataFrame by Setting the name Attribute
- Set the Name of Index Column of a DataFrame Using rename_axis() Method
- pandas.Index.set_names#
Как переименовать индекс в 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 Set Index Name to DataFrame
Use pandas.DataFrame.rename_axis() to set the index name/title, in order to get the index use DataFrame.index.name property and the same could be used to set the index name as well. When you create a DataFrame, by default pandas creates an index name as ‘Index’ . By using the approaches mentioned in this article, you can set the custom name to index.
Alternatively, index name can be set using df.index.rename() , df.index.set_names() .
1. Quick Examples of pandas Set Index Name
In case you hurry, below are some quick examples of how to set the index name to pandas DataFrame.
Now, let’s create a DataFrame with a few rows and columns, execute these examples and validate results. Our DataFrame contains column names Courses , Fee , Duration , and Discount .
index_labels=['r1','r2','r3','r4'] df = pd.DataFrame(technologies,index=index_labels) print(df)
By default, the DataFrame assigns an Index name as Index and this is not shown on the DataFrame output.
2. Get Index Name From pandas DataFrame
As I said above, pandas assign a default name to the Index column, you can get this using DataFrame.index.name
Now, let’s set a custom Index name to the DataFrame.
3. Assign Column as Index using set_index()
Use pandas.DataFrame.set_index() method to set a column as an index. In the below example, I am setting the column Courses as Index. When you do this, the column name is assigned as an index name and it will be removed from columns.
4. pandas Set Index Name using rename_axis()
You can also rename the Index name using rename_axis() , just pass the index name you wanted as an argument to this method. This method also takes several arguments like inplace=True , axis=1 and more, refer to pandas documentation for more details.
It sets the name of the index column of the DataFrame to Courses1 . Now let’s see how to rename the axis of the Index column. For example, set the axis name as Courses_Name .
You can also use the parameters index and column in order to get pandas index title/name. For example-
5. Using DataFrame.index.rename() get Pandas Index Title/Name
In this section, I will use df.index.rename with inplace=True parameter in order to set the index name on the existing DataFrame.
6. Add Multiple Index Using DataFrame.set_index()
By using DataFrame.set_index() you can also set multiple existing columns as indexes. Below examples append columns Courses and Duration to row Index.
7. Rename Multi Level Index Names Using index.set_names()
By using DataFrame.index.set_names() you can change the index of a specific level when you have multiple levels of row indexes. For example-
8. Rename Multiple/All Level of Indexes
When you have multiple rows indices and if you wanted to rename multiple indices at the same time, use DataFrame.index.rename() . Note that you need to specify all indices as a param.
9. Complete Examples of pandas Set Index Name
index_labels=['r1','r2','r3','r4'] df = pd.DataFrame(technologies,index=index_labels) print(df) # Get name of the index column of DataFrame. df.index.name 'Index' df.index.name='Index1' print(df) # Get pandas index/name by set_index. df = pd.DataFrame(technologies).set_index('Courses') print(df) # To get Index and Column names. print (df.index.name) print (df.columns.name) # Rename a column by rename_axis method. df = df.rename_axis('Courses1') print(df) # Rename index column by rename_axis() method df = pd.DataFrame(technologies).set_index('Courses').rename_axis('Courses_Name', axis=1) print(df) # Get pandas index title/name by index and Column parameter. df = df.rename_axis(index='RowNumber', columns="Row") print(df) # Removing index and columns names to set it none. df = df.rename_axis(index=None, columns=None) print(df) # Using de.indx.rename get pandas index title/name. df.index.rename('Row', inplace=True) print(df) # Add Multilevel index using set_index() df2 = df.set_index(['Courses', 'Duration'], append=True) print(df2) # Rename Single index from multi Level df2.index = df2.index.set_names('Courses_Duration', level=2) print(df2) # Rename All indexes df2.index=df2.index.rename(['Row','Courses_Name','Courses_Duration']) print(df2)
10. Conclusion
In this article, you have learned about getting and setting index column name using set_index(), rename_axis() methods, also rename index by rename_axis() with several aparamters.
Related Articles
Reference
You may also like reading:
Get and Set Pandas DataFrame Index Name
- Get the Name of the Index Column of a DataFrame
- Set the Name of the Index Column of a DataFrame by Setting the name Attribute
- Set the Name of Index Column of a DataFrame Using rename_axis() Method
This tutorial explains how we can set and get the name of the index column of a Pandas DataFrame. We will use the below example DataFrame in the article.
import pandas as pd my_df = pd.DataFrame( 'Applicant': ['Ratan', 'Anil', 'Mukesh', 'Kamal'], 'Hometown': ['Delhi', 'Pune', 'Dhangadi', 'Kolkata'], 'Score': [85,87,90,89], >,index=["2021-01-03","2021-01-04","2021-01-05","2021-01-06"]) print(my_df)
Applicant Hometown Score 2021-01-03 Ratan Delhi 85 2021-01-04 Anil Pune 87 2021-01-05 Mukesh Dhangadi 90 2021-01-06 Kamal Kolkata 89
Get the Name of the Index Column of a DataFrame
We can get the name of the index column of the DataFrame using the name attribute of the index column.
import pandas as pd my_df = pd.DataFrame( 'Applicant': ['Ratan', 'Anil', 'Mukesh', 'Kamal'], 'Hometown': ['Delhi', 'Pune', 'Dhangadi', 'Kolkata'], 'Score': [85,87,90,89], >,index=["2021-01-03","2021-01-04","2021-01-05","2021-01-06"]) print("The DataFrame is:") print(my_df,"\n") print("Name of Index Column of the DataFrame is:") print(my_df.index.name)
The DataFrame is: Applicant Hometown Score 2021-01-03 Ratan Delhi 85 2021-01-04 Anil Pune 87 2021-01-05 Mukesh Dhangadi 90 2021-01-06 Kamal Kolkata 89 Name of Index Column of the DataFrame is: None
It gets the name of the index column of my_df DataFrame as None as we have not set the index column’s name for my_df DataFrame.
Set the Name of the Index Column of a DataFrame by Setting the name Attribute
We simply set the value of the name attribute of the index of the DataFrame to set the name of the index column of the DataFrame.
import pandas as pd my_df = pd.DataFrame( 'Applicant': ['Ratan', 'Anil', 'Mukesh', 'Kamal'], 'Hometown': ['Delhi', 'Pune', 'Dhangadi', 'Kolkata'], 'Score': [85,87,90,89], >,index=["2021-01-03","2021-01-04","2021-01-05","2021-01-06"]) print("Initial DataFrame:") print(my_df,"\n") my_df.index.name="Date" print("DataFrame after setting the name of Index Column:") print(my_df,"\n") print("Name of Index Column of the DataFrame is:") print(my_df.index.name)
Initial DataFrame: Applicant Hometown Score 2021-01-03 Ratan Delhi 85 2021-01-04 Anil Pune 87 2021-01-05 Mukesh Dhangadi 90 2021-01-06 Kamal Kolkata 89 DataFrame after setting the name of Index Column: Applicant Hometown Score Date 2021-01-03 Ratan Delhi 85 2021-01-04 Anil Pune 87 2021-01-05 Mukesh Dhangadi 90 2021-01-06 Kamal Kolkata 89 Name of Index Column of the DataFrame is: Date
It sets the name of index of my_df to Date .
Set the Name of Index Column of a DataFrame Using rename_axis() Method
We can pass the index column’s name as an argument to the rename_axis() method to set the name of the index column of the DataFrame.
import pandas as pd my_df = pd.DataFrame( 'Applicant': ['Ratan', 'Anil', 'Mukesh', 'Kamal'], 'Hometown': ['Delhi', 'Pune', 'Dhangadi', 'Kolkata'], 'Score': [85,87,90,89], >,index=["2021-01-03","2021-01-04","2021-01-05","2021-01-06"]) print("Initial DataFrame:") print(my_df,"\n") my_df=my_df.rename_axis('Date') print("DataFrame after setting the name of Index Column:") print(my_df,"\n") print("Name of Index Column of the DataFrame is:") print(my_df.index.name)
Initial DataFrame: Applicant Hometown Score 2021-01-03 Ratan Delhi 85 2021-01-04 Anil Pune 87 2021-01-05 Mukesh Dhangadi 90 2021-01-06 Kamal Kolkata 89 DataFrame after setting the name of Index Column: Applicant Hometown Score Date 2021-01-03 Ratan Delhi 85 2021-01-04 Anil Pune 87 2021-01-05 Mukesh Dhangadi 90 2021-01-06 Kamal Kolkata 89 Name of Index Column of the DataFrame is: Date
It sets the name of the index column of the DataFrame my_df to Date using the rename_axis() method.
Suraj Joshi is a backend software engineer at Matrice.ai.
pandas.Index.set_names#
If the index is a MultiIndex and names is not dict-like, level(s) to set (None for all levels). Otherwise level must be None.
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 without level.
>>> idx = pd.Index([1, 2, 3, 4]) >>> idx Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Index([1, 2, 3, 4], dtype='int64', name='quarter')
>>> idx = pd.MultiIndex.from_product([['python', 'cobra'], . [2018, 2019]]) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], ) >>> idx = idx.set_names(['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['species', 'year'])
When renaming levels with a dict, levels can not be passed.
>>> idx.set_names('kind': 'snake'>) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['snake', 'year'])