ZhangZhihui's Blog  
import pandas as pd

df = pd.DataFrame([[2001, 'D', 2],
                   [2004, 'T', 3],
                   [2003, 'T', 5],
                   [2001, 'T', 4],
                   [2004, 'D', 7]],
                  columns=['year', 'type', 'cnt'])
df_year = df.groupby(['year', 'type']).sum('cnt')
print(df_year)
print(df_year.index)
print(df_year.loc[2001])              # Select first level
print(df_year.xs('T', level='type'))  # Select second level
print(df_year.loc[(2004, 'D')])

 

Output:

 

The xs() method (short for cross-section) is a powerful tool in Pandas specifically designed for pulling data from a MultiIndex (hierarchical index) DataFrame.

While the standard .loc[] or .iloc[] methods are great for simple slicing, xs() is much cleaner when you want to select data at a specific "level" of your index without having to specify all the other levels.


1. Basic Syntax

Python
 
df.xs(key, axis=0, level=None, drop_level=True)
  • key: The label you are looking for.

  • axis: 0 for rows (default), 1 for columns.

  • level: Which level of the index the key belongs to (can be the level's name or its integer index).

  • drop_level: If True (default), the level you are slicing on is removed from the resulting DataFrame.

 

posted on 2022-01-07 22:14  ZhangZhihuiAAA  阅读(23)  评论(0)    收藏  举报