使用loc方法配合切片操作,可以轻松地选择多级索引中的特定行。示例代码如下:
import pandas as pd
# 创建一个有多级索引的dataframe
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 
                   'C': [9, 10, 11, 12]}, 
                  index=pd.MultiIndex.from_tuples(
                           [('foo', 'one'), ('foo', 'two'),
                            ('bar', 'one'), ('bar', 'two')],
                           names=['first', 'second']))
# 选择first列为'foo',second列为'one'和'two'的行
selected_rows = df.loc[(['foo', 'bar'], ['one', 'two']), :]
print(selected_rows)
输出:
             A  B   C
first second         
foo   one     1  5   9
      two     2  6  10
bar   one     3  7  11
      two     4  8  12
在上面的代码中,loc方法通过传递一个元组(即一个由索引标签列表构成的元组)来选择特定的行。在这个例子中,我们选择了first列为'foo'和'bar',second列为'one'和'two'的所有行。
下一篇:币市资料爬虫