Skip to content

Unable to retrieve same-index dataframe with the last item per group #7883

Closed
@amelio-vazquez-reina

Description

@amelio-vazquez-reina

The original thread is here.

> df
                   C         D  E
A    B                           
bar  one   -1.350006  0.260339  2
     three -0.236451 -0.056614  0
flux six   -0.515571 -0.155078  1
     three -0.365032  1.055669  2
foo  five   1.145811  1.514191  0
     one   -0.108427 -0.643262  2
     two    0.286897  0.405798  2
     two   -1.452286  1.149264  2

The goal is to get a dataframe with the same index with each entry having the last value in the groups associated with A, i.e.

> df
                   C         D  E
A    B                           
bar  one   -0.236451 -0.056614  2
     three -0.236451 -0.056614  2
flux six   -0.365032  1.055669  2
     three -0.365032  1.055669  2
foo  five  -1.452286  1.149264  2
     one   -1.452286  1.149264  2
     two   -1.452286  1.149264  2
     two   -1.452286  1.149264  2

However, none of the following work:

  • df.groupby(level='A').apply(lambda x: x[-1])
  • df.groupby(level='A').transform(pd.Series.last)
  • df.groupby(level='A').transform(lambda x: x.iloc[-1])

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions