简体   繁体   中英

Slice a specific row out of pandas groupby dataframe

I need to slice a particular row out of a groupby dataframe using 2 columns titles (The image is provided).I need the output of "Age" for a given Gender and Country.

Output of the groupby dataframe

Now that you didnt give data. Lets use free data from seaborn

Data

import pandas as pd
import seaborn as sns
sns.set()
tips = sns.load_dataset("tips")
tips

Groupby to get similar result to yours

df=tips.groupby(['sex','time'])['tip'].sum().to_frame()
df

Several ways to slice multi index for row;

##Silce Male Dinner
df.loc['Male','Dinner',:]

##Silce Female Dinner and Lunch
df.loc['Female',:]

#slice(None) to select all the contents of that level.
df.loc[(slice(None),'Lunch'),:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM