pandas设置多列索引
时间: 2023-02-27 21:47:06 浏览: 65
在 Pandas 中,可以使用 `set_index` 方法来设置多列索引。具体的代码示例如下:
```
import pandas as pd
# 创建一个简单的 DataFrame
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
# 设置多列索引
df = df.set_index(['A', 'B'])
# 显示 DataFrame
print(df)
```
输出结果:
```
C D
A B
foo one 1 10
bar one 2 20
foo two 3 30
bar three 4 40
foo two 5 50
bar two 6 60
foo one 7 70
foo three 8 80
```
在上面的代码中,我们使用了 `set_index` 方法来将列 `A` 和列 `B` 设置为 DataFrame 的多列索引。