Python | Панды MultiIndex.to_frame ()
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Pandas MultiIndex.to_frame() function create a DataFrame with the levels of the MultiIndex as columns.
Syntax: MultiIndex.to_frame(index=True)
Parameters :
index : Set the index of the returned DataFrame as the original MultiIndex.Returns : DataFrame : a DataFrame containing the original MultiIndex data.
Example #1: Use MultiIndex.to_frame() function to construct a dataframe using the MultiIndex levels as the column and index.
# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_tuples([(10, "Ten"), (10, "Twenty"), (20, "Ten"), (20, "Twenty")], names =["Num", "Char"]) # Print the MultiIndexprint(midx) |
Выход :
Now let’s construct the dataframe from the MultiIndex.
# Construct the DataFramemidx.to_frame(index = True) |
Output :
As we can see in the output, the function has constructed the Dataframe using the MultiIndex. Notice the index of the dataframe is constructed using the levels of the MultiIndex.
Example #2: Use MultiIndex.to_frame() function to construct a DataFrame using the MultiIndex. Do not use the MultiIndex levels to construct the index of the Dataframe.
# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_tuples([(10, "Ten"), (10, "Twenty"), (20, "Ten"), (20, "Twenty")], names =["Num", "Char"]) # Print the MultiIndexprint(midx) |
Выход :
Now let’s create a dataframe using the midx MultiIndex.
# Create Dataframe with new index values.midx.to_frame(index = False) |
Выход :
Как видно из выходных данных, функция вернула DataFrame с другим значением индекса.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.