2

I have a Pandas dataframe with a multiindex

             A         B
year  age  
1895   0     10        12
1895   1     13        14
...
1965   0     34        45
1965   1     41        34
      ...
1965  50     56        22
1966   0     10        34
...

I would like to get all ages between two values (e.g. 10 and 20) summed for column A (and B). I played around a bit with .xs e.g.

pops.xs(20, level='age')

gives all the age 20 for each year, but I cannot get this for multiple ages (and summed).

Eg. for 0 and 1 I would like to get

Any suggetions for an elegant (efficient) way to do that?

          A         B
year    
1895      23        26
...
1965      75        79
...
1
  • df.sum(level=0) Commented May 30, 2018 at 15:47

2 Answers 2

1

Use query for select with sum per first level years:

print (df)
           A   B
year age        
1895 8    10  12
     12   13  14
1965 0    34  45
     14   41  34
     12   56  22
1966 0    10  34

df = df.query('10 <= age <= 20').sum(level=0)
print (df)
       A   B
year        
1895  13  14
1965  97  56

Detail:

print (df.query('10 <= age <= 20'))
           A   B
year age        
1895 12   13  14
1965 14   41  34
     12   56  22

Another solution is use Index.get_level_values for index and filter by boolean indexing:

i = df.index.get_level_values('age')
print (i)
Int64Index([8, 12, 0, 14, 12, 0], dtype='int64', name='age')

df = df[(i >= 10) & (i <= 20)].sum(level=0)
print (df)
       A   B
year        
1895  13  14
1965  97  56
Sign up to request clarification or add additional context in comments.

Comments

0

You can use loc and slice to select the part of the DF you want such as:

df.loc[(slice(None),slice(10,20)),:].sum(level=0)

where (slice(None),slice(10,20)) allows you to keep all indexes for all years and age between 10 and 20 included

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.