简体   繁体   中英

How to loop over grouped DataFrames? Python

I have this grouped DF:

Publisher                     Year  
10TACLE Studios               2006.0     0.02
                              2007.0     0.09
1C Company                    2009.0     0.01
                              2011.0     0.09
20th Century Fox Video Games  1981.0     1.35
                              1982.0     0.59
2D Boy                        2008.0     0.04
3DO                           1998.0     0.40
                              1999.0     4.14
                              2000.0     3.08
                              2001.0     1.45
                              2002.0     0.60
                              2003.0     0.45
49Games                       2009.0     0.04
505 Games                     2002.0     0.29
                              2003.0     0.10
                              2004.0     0.89
                              2005.0     1.27
                              2006.0     7.49
                              2007.0    10.43

I want to know what 'Publisher' has increased its Sales from 2006 to 2016. I have tried many ways I saw in other questions but nothing works for me.

I have an idea, first.loc to have only rows from 2006 to 2016 (it's done) and then grab the first and last value of each Publisher (For example, for 3DO, 0.40 and 0.45) and subtract: 0.45-0.40, if it's positive I append it in a list.

Assuming a Series as input, you can filter, sort_index and use a groupby.first / last :

g = (s.loc[(slice(None), slice(2006,2016))]  # keep only years 2006-2016
      .sort_index(level='Year')              # sort Years
      .groupby(level='Publisher')            # form groups
     )

# get last - first year's value and only keep positive values
out = g.last().sub(g.first()).loc[lambda s: s.gt(0)]

output:

Publisher
10TACLE Studios    0.07
1C Company         0.08
505 Games          2.94
Name: Value, dtype: float64

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