Python | Pandas Index.set_names ()
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Pandas Index.set_names()
function set new names on index. For the given Index it resets the name attribute for that Index. It defaults to returning new index. The functions can also be used to reset the name attribute of the multi-index.
Syntax: Index.set_names(names, level=None, inplace=False)
Parameters :
names : [str or sequence] name(s) to set
level : If the index is a MultiIndex (hierarchical), level(s) to set (None for all levels). Otherwise level must be None
inplace : [bool] if True, mutates in placeReturns : new index (of same type and class…etc) [if inplace, returns None]
Example #1: Use Index.set_names()
function create an anonymous Index and set its name using the name parameter.
# importing pandas as pd import pandas as pd # Creating the index and setting the name pd.Index([ "Beagle" , "Pug" , "Labrador" , "Pug" , "Mastiff" , None , "Beagle" ]).set_names( "Dog_breeds" ) |
Output :
As we can see in the output, the function has reset the name attribute of the anonymous Index.
Example #2: Use Index.set_names()
function to reset the name attribute of the multi-index.
# importing pandas as pd import pandas as pd # Creating the multi-index form tuples midx = pd.MultiIndex.from_tuples([( "Sam" , 21 ), ( "Norah" , 25 ), ( "Jessica" , 32 ), ( "Irwin" , 24 )], names = [ "Name" , "Age" ]) # Print the Multi-Index midx |
Output :
As we can see in the output, the name attribute of midx multi-index is set to ‘Name’ and ‘Age’. Let’s reset these names to be ‘Student_Name’ and ‘Student_Age’
# to reset the name of the midx midx.set_names([ "Student_Name" , "Student_Age" ]) |
Выход :
Как видно из выходных данных, функция сбросила атрибут name мультииндекса midx.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.