How to avoid a chained apply when selecting from multiindex?

Cleb

I have a dataframe like this:

import numpy as np
import pandas as pd


df = pd.DataFrame({
    'ind1': list('AAABBBCCC'),
    'ind2': list(map(int, list('123123123'))),
    'val1': [0, 1, 2, -1, -4, -5, 10, 11, 4],
    'val2': [0.1, 0.2, -0.2, 0.1, 0.2, 0.2, -0.1, 2, 0.1]
})

df = df.set_index(['ind1', 'ind2'])

           val1  val2
ind1 ind2            
A    1        0   0.1
     2        1   0.2
     3        2  -0.2
B    1       -1   0.1
     2       -4   0.2
     3       -5   0.2
C    1       10  -0.1
     2       11   2.0
     3        4   0.1

I want to select all entries for which the absolute value of differences between the values in val1 are increasing.

I currently do it as follows:

m_incr = (
    df.groupby('ind1')['val1']
      .apply(lambda x: np.diff(abs(x)))
      .apply(lambda x: all(eli > 0 for eli in x))
)

df_incr = df[m_incr[df.index.get_level_values('ind1')].values]

which gives me the desired outcome:

           val1  val2
ind1 ind2            
A    1        0   0.1
     2        1   0.2
     3        2  -0.2
B    1       -1   0.1
     2       -4   0.2
     3       -5   0.2

My question is whether there is a more straightforward/efficient way that avoids the chained applys.

jezrael

Use GroupBy.transform for return Series with same size like original DataFrame:

mask = df.groupby('ind1')['val1'].transform(lambda x: (np.diff(abs(x)) > 0).all())

And then filter by mask with boolean indexing:

print (df[mask])

All together:

print (df[df.groupby('ind1')['val1'].transform(lambda x: (np.diff(abs(x)) > 0).all())])

           val1  val2
ind1 ind2            
A    1        0   0.1
     2        1   0.2
     3        2  -0.2
B    1       -1   0.1
     2       -4   0.2
     3       -5   0.2

Detail:

print (mask)
ind1  ind2
A     1        True
      2        True
      3        True
B     1        True
      2        True
      3        True
C     1       False
      2       False
      3       False
Name: val1, dtype: bool

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How do I assign to a Pandas DataFrame while selecting by MultiIndex name?

分類Dev

Creating a new level for one index in a multiindex when using groupby and apply

分類Dev

How can I remove pins from google maps when selecting new location from select menu?

分類Dev

How can I stop workspaces from switching automatically to other workspaces when selecting different applications?

分類Dev

How to limit time when SELECTing (MYSQL)

分類Dev

How can I avoid "no input files" error from sed, when run from xargs?

分類Dev

How to show information by selecting a date from the list

分類Dev

How to avoid quadratic computation resulting from double 'for loop' when computing distances between vectors

分類Dev

How to avoid 'Invalid date' prefix in result when converting from milliseconds (13 digits)

分類Dev

Issue Selecting DB value from DropDown List when Page is generated

分類Dev

input string not in correct format when selecting value from dropdown

分類Dev

Segue between multiple detail views when selecting from tableview

分類Dev

Fill a JList with database entries when selecting from a ComboBox

分類Dev

IllegalStateException when trying selecting photo from Google Photos app

分類Dev

How to apply rolling function when all variables in window from multiple columns are required

分類Dev

How to compare the data and choose the TOP 2 from multiIndex dataframe in pandas?

分類Dev

How to avoid coupling when using useReducer?

分類Dev

How to disable multiple select tag when selecting one?

分類Dev

How to avoid "passphrase is too short" from golang

分類Dev

How to avoid an invalid overload from the std library?

分類Dev

How to avoid throwing exception from finally block

分類Dev

How to avoid web browser warning when my site use HTTPS protocol, and it's pages include images from sites without HTTPS?

分類Dev

How to open a div selecting a value from dropdown in jQuery

分類Dev

How to reshape multiindex dataframe

分類Dev

Avoid RecyclerView from showing scrollbar when notifyItemChanged being called

分類Dev

How to apply CSS code from array in AngularJS?

分類Dev

How to avoid hardware compability problems when shopping for a laptop to run Linux on?

分類Dev

How to avoid slow collapse when using bootstrap collapse and div in a table

分類Dev

How to avoid duplicate key error in swift when iterating over a dictionary

Related 関連記事

  1. 1

    How do I assign to a Pandas DataFrame while selecting by MultiIndex name?

  2. 2

    Creating a new level for one index in a multiindex when using groupby and apply

  3. 3

    How can I remove pins from google maps when selecting new location from select menu?

  4. 4

    How can I stop workspaces from switching automatically to other workspaces when selecting different applications?

  5. 5

    How to limit time when SELECTing (MYSQL)

  6. 6

    How can I avoid "no input files" error from sed, when run from xargs?

  7. 7

    How to show information by selecting a date from the list

  8. 8

    How to avoid quadratic computation resulting from double 'for loop' when computing distances between vectors

  9. 9

    How to avoid 'Invalid date' prefix in result when converting from milliseconds (13 digits)

  10. 10

    Issue Selecting DB value from DropDown List when Page is generated

  11. 11

    input string not in correct format when selecting value from dropdown

  12. 12

    Segue between multiple detail views when selecting from tableview

  13. 13

    Fill a JList with database entries when selecting from a ComboBox

  14. 14

    IllegalStateException when trying selecting photo from Google Photos app

  15. 15

    How to apply rolling function when all variables in window from multiple columns are required

  16. 16

    How to compare the data and choose the TOP 2 from multiIndex dataframe in pandas?

  17. 17

    How to avoid coupling when using useReducer?

  18. 18

    How to disable multiple select tag when selecting one?

  19. 19

    How to avoid "passphrase is too short" from golang

  20. 20

    How to avoid an invalid overload from the std library?

  21. 21

    How to avoid throwing exception from finally block

  22. 22

    How to avoid web browser warning when my site use HTTPS protocol, and it's pages include images from sites without HTTPS?

  23. 23

    How to open a div selecting a value from dropdown in jQuery

  24. 24

    How to reshape multiindex dataframe

  25. 25

    Avoid RecyclerView from showing scrollbar when notifyItemChanged being called

  26. 26

    How to apply CSS code from array in AngularJS?

  27. 27

    How to avoid hardware compability problems when shopping for a laptop to run Linux on?

  28. 28

    How to avoid slow collapse when using bootstrap collapse and div in a table

  29. 29

    How to avoid duplicate key error in swift when iterating over a dictionary

ホットタグ

アーカイブ