文章目录
https://www.cnblogs.com/beyondChan/p/10926788.html
b
多层索引变一层
df1.columns = ['_'.join(col) for col in df1.columns.values]
增加一行/列
a.loc[:, ('支付买家数')] = b
a
b
变为多层索引
b2 = b.set_index(['用户手机号', '月份']).unstack('月份')
b2
交换索引等级
b3 = b2.swaplevel(axis=1)
b3
swaplevel(i=-2,j=-1,axis=1),level=i和level=j的索引对换
b4 = b3.sort_index(axis=1)
b4
生成多重索引 笛卡尔积
pd.DataFrame(index=pd.MultiIndex.from_product([['a','b'],['c','d']]))
选取索引
df.index.levels
pr_cnt2.columns.get_level_values(1).isin(['GMV', 'UV'])
查看索引层级
df.columns.lexsort_depth
df.columns.levshape
多层索引查询
方法一:xs
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.xs.html
查找,columns为 2022-03-31的数据
df_mom.xs('2022-03-31', axis=1, level=1)
方法二:df.columns.get_level_values
https://www.5axxw.com/questions/content/htre42
df_mom.loc[:, df_mom.columns.droplevel(0).isin(['2022-02-28', '2023-01-31', '2023-02-28'])]
df_mom.loc[:, df_mom.columns.get_level_values(1)=='2022-03-31']
多层索引聚合
df.sum(level=0, axis=1)