Pandas分层索引是一种在DataFrame和Series中使用的索引技术,能够处理多维数据,使得对于数据的分组和展示更加方便和灵活。在分层索引中,每层索引都是针对数据集中的某个特定维度的,这些层次索引可以根据需要自由组合,形成多级索引,从而满足数据分析任务的细粒度需求。
1.通过列表创建分层索引:
import pandas as pd
import numpy as np
arrays = [np.array(['a', 'a', 'b', 'b']), np.array(['red', 'blue', 'red', 'blue'])]
df = pd.DataFrame(np.random.randn(4, 3), index=arrays)
df
2.通过元组创建分层索引:
import pandas as pd
import numpy as np
tuples = list(zip(*[['a', 'a', 'b', 'b'], ['red', 'blue', 'red', 'blue']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(4, 2), index=index)
df
3.通过字典创建分层索引:
import pandas as pd
import numpy as np
dic = {'first': ['a', 'a', 'b', 'b'],
'second': ['red', 'blue', 'red', 'blue']}
df = pd.DataFrame(np.random.randn(4, 2), pd.MultiIndex.from_frame(pd.DataFrame(dic)))
df
1.通过loc索引器
import pandas as pd
import numpy as np
arrays = [np.array(['a', 'a', 'b', 'b']), np.array(['red', 'blue', 'red', 'blue'])]
df = pd.DataFrame(np.random.randn(4, 3), index=arrays)
df.loc['a']
df.loc[('a', 'red')]
df.loc[(['a', 'b'], ['red', 'blue']), :]
2.通过交换索引
import pandas as pd
import numpy as np
arrays = [np.array(['a', 'a', 'b', 'b']), np.array(['red', 'blue', 'red', 'blue'])]
df = pd.DataFrame(np.random.randn(4, 3), index=arrays)
df_swap = df.swaplevel(0, 1)
df_swap.sort_index(inplace=True)
3.分组操作
import pandas as pd
import numpy as np
arrays = [np.array(['a', 'a', 'b', 'b']), np.array(['red', 'blue', 'red', 'blue'])]
df = pd.DataFrame(np.random.randn(4, 3), index=arrays)
grouped = df.groupby(level=0).mean()
grouped = df.groupby(level=[0,1]).sum()
例子:使用Pandas分层索引完成美国国家篮球协会(NBA)的球员数据统计
1.导入数据集,选取属于2016-2017年度收入排名前10的球员数据
import pandas as pd
import numpy as np
players_url = 'https://media.geeksforgeeks.org/wp-content/uploads/nba.csv'
players = pd.read_csv(players_url)
top_players = players[players['season_end'] == 2017].sort_values(by='salary',
ascending=False).head(10)
2.以球队和名字为第一第二层索引,对球员数据进行分层索引
top_players.set_index(['team', 'name'], inplace=True)
3.以多级索引对数据集中的某个维度进行聚合计算
top_players.groupby(level=[0,1]).mean()
本文链接:http://task.lmcjl.com/news/4434.html