get first and last values in a groupby

Brian

I have a dataframe df

df = pd.DataFrame(np.arange(20).reshape(10, -1),
                  [['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'],
                   ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']],
                  ['X', 'Y'])

How do I get the first and last rows, grouped by the first level of the index?

I tried

df.groupby(level=0).agg(['first', 'last']).stack()

and got

          X   Y
a first   0   1
  last    6   7
b first   8   9
  last   12  13
c first  14  15
  last   16  17
d first  18  19
  last   18  19

This is so close to what I want. How can I preserve the level 1 index and get this instead:

      X   Y
a a   0   1
  d   6   7
b e   8   9
  g  12  13
c h  14  15
  i  16  17
d j  18  19
  j  18  19
piRSquared

Option 1

def first_last(df):
    return df.ix[[0, -1]]

df.groupby(level=0, group_keys=False).apply(first_last)

enter image description here


Option 2 - only works if index is unique

idx = df.index.to_series().groupby(level=0).agg(['first', 'last']).stack()
df.loc[idx]

Option 3 - per notes below, this only makes sense when there are no NAs

I also abused the agg function. The code below works, but is far uglier.

df.reset_index(1).groupby(level=0).agg(['first', 'last']).stack() \
    .set_index('level_1', append=True).reset_index(1, drop=True) \
    .rename_axis([None, None])

Note

per @unutbu: agg(['first', 'last']) take the firs non-na values.

I interpreted this as, it must then be necessary to run this column by column. Further, forcing index level=1 to align may not even make sense.

Let's include another test

df = pd.DataFrame(np.arange(20).reshape(10, -1),
                  [list('aaaabbbccd'),
                   list('abcdefghij')],
                  list('XY'))

df.loc[tuple('aa'), 'X'] = np.nan

def first_last(df):
    return df.ix[[0, -1]]

df.groupby(level=0, group_keys=False).apply(first_last)

enter image description here

df.reset_index(1).groupby(level=0).agg(['first', 'last']).stack() \
    .set_index('level_1', append=True).reset_index(1, drop=True) \
    .rename_axis([None, None])

enter image description here

Sure enough! This second solution is taking the first valid value in column X. It is now nonsensical to have forced that value to align with the index a.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

get first and last values in a groupby

From Dev

Groupby search first and last True values

From Dev

Pandas DataFrame groupby two columns and get first and last

From Dev

Pandas DataFrame groupby two columns and get first and last

From Dev

get first and last value of a groupby object in laravel 5 and mysql

From Dev

How to get first and last values from list<string>?

From Java

Get the first and last row values by unique id in a dataframe

From Dev

vb.net get the *values* of the first and last lines of an array

From Dev

SSRS How to get the first and last values of a matrix row group?

From Dev

Get values from first and last row per group

From Dev

how to get first,last and other values of object in javascript?

From Dev

Excel Formula To Get First and Last Non-Zero Values

From Dev

How to get the first and last values in jquery with a specific style?

From Dev

Get values of first record and last record by date in mysql subquery

From Java

Groupby ID, sort by Time, and divide last by first

From Java

FIRST & LAST values in Oracle SQL

From Dev

Order values for minimum values e get first and last name from vendor

From Dev

Get first and last day of last month?

From Dev

Get first AND last element with SQLAlchemy

From Dev

get first and last element in array

From Dev

Get first and last object in selector

From Dev

Get first and last primary key values from SQLlite db table in Java?

From Dev

How to get values not indexed in the first or in the last in a comma separated string but in the middle of the string in MySQL

From Dev

How to get last group in Pandas' groupBy?

From Dev

Is there a way to get the number of occurrences of the last value in a groupby?

From Dev

Is there a way to get the number of occurrences of the last value in a groupby?

From Dev

How to get last quarter and last year values

From Dev

SessionStorage, get only last values

From Dev

Get first instance and Get last instance of string

Related Related

  1. 1

    get first and last values in a groupby

  2. 2

    Groupby search first and last True values

  3. 3

    Pandas DataFrame groupby two columns and get first and last

  4. 4

    Pandas DataFrame groupby two columns and get first and last

  5. 5

    get first and last value of a groupby object in laravel 5 and mysql

  6. 6

    How to get first and last values from list<string>?

  7. 7

    Get the first and last row values by unique id in a dataframe

  8. 8

    vb.net get the *values* of the first and last lines of an array

  9. 9

    SSRS How to get the first and last values of a matrix row group?

  10. 10

    Get values from first and last row per group

  11. 11

    how to get first,last and other values of object in javascript?

  12. 12

    Excel Formula To Get First and Last Non-Zero Values

  13. 13

    How to get the first and last values in jquery with a specific style?

  14. 14

    Get values of first record and last record by date in mysql subquery

  15. 15

    Groupby ID, sort by Time, and divide last by first

  16. 16

    FIRST & LAST values in Oracle SQL

  17. 17

    Order values for minimum values e get first and last name from vendor

  18. 18

    Get first and last day of last month?

  19. 19

    Get first AND last element with SQLAlchemy

  20. 20

    get first and last element in array

  21. 21

    Get first and last object in selector

  22. 22

    Get first and last primary key values from SQLlite db table in Java?

  23. 23

    How to get values not indexed in the first or in the last in a comma separated string but in the middle of the string in MySQL

  24. 24

    How to get last group in Pandas' groupBy?

  25. 25

    Is there a way to get the number of occurrences of the last value in a groupby?

  26. 26

    Is there a way to get the number of occurrences of the last value in a groupby?

  27. 27

    How to get last quarter and last year values

  28. 28

    SessionStorage, get only last values

  29. 29

    Get first instance and Get last instance of string

HotTag

Archive