如何在 Pandas 中创建多索引?
要在Pandas中创建多索引,我们可以将groupby与列列表一起使用。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧。
打印DataFrame计数的索引。
使用groupby获取不同级别的分层索引并对其进行计数。
打印在步骤4中设置的多索引。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:\n", df
print "\nDefault index: ", df.count().index
df1 = df.groupby(["x", "y"]).count()
print "\nMulti index is like: \n", df1.index输出结果Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 Default index: Index(['x', 'y', 'z'], dtype='object') Multi index is like: MultiIndex([(1, 5), (2, 1), (5, 4), (9, 10)], names=['x', 'y'])