Как создать сводную таблицу с несколькими индексами из листа Excel с помощью Pandas в Python?
Термин «Сводная таблица» можно определить как функцию Pandas, используемую для создания сводной таблицы в стиле электронной таблицы как DataFrame. Его можно создать с помощью метода pivot_table ().
Syntax: pandas.pivot_table(data, index=None)
Parameters:
data : DataFrame
index: column, Grouper, array, or list of the previousindex: It is the feature that allows you to group your data.
Returns: DataFrame
Примечание. Мы можем дополнительно отфильтровать таблицу, добавив необязательные параметры.
Example 1: Link to the CSV File: CSV FILE
We can have a look at the data by running the following program:
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv("GeeksForGeeks.csv") # Print the dataframe df |
Выход:

We know that the index is the feature that allows us to group our data and specifying multiple columns as the indices in pivot function increases the level of details and grouping the data.
Keeping a single index in the table:
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv("GeeksForGeeks.csv") # Print the resultant tableprint(pd.pivot_table(df,index=["Country"])) |
Output:

As we can see that the grouping is done country wise and the numerical data is printed as the average of all the values with regard to the specified index.
Now, Keeping multiple indices in the table:
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv("GeeksForGeeks.csv") # Print the resultant tableprint(pd.pivot_table(df,index=["Country","Salary"])) |
Output:

Example 2: Link to the CSV File: CSV FILE
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv("GeeksForGeeks_1.csv") # Print the dataframe df |
Output:

Keeping the number of centuries scored by players and their names as indices, we get:
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df=pd.read_csv("dataset/new_players.csv") # Print the resultant tableprint(pd.pivot_table(df,index=["century","name"])) |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.