Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to partition a dataframe into dataframes with no missing and contiguous indices?

Suppose I have the following DataFrame

index  Value
  0     'A'
  1     'B'
  2    pd.NA
  3    pd.NA
  4     'C'
  5    pd.NA

Then, I’m looking for a function that returns the next two DataFrames:

First:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index  Value
  0     'A'
  1     'B'

Second:

index  Value
  4     'C'

>Solution :

You can build a mask of NAs (with isna), form groups of successive non-NAs with cumsum and split with groupby:

m = df['Value'].isna()

dfs = [g for _,g in df[~m].groupby(m.cumsum())]

Output:

[   index Value
 0      0     A
 1      1     B,
    index Value
 4      4     C]

Intermediates:

   index Value   isna      ~  cumsum
0      0     A  False   True       0
1      1     B  False   True       0
2      2   NaN   True  False       1
3      3   NaN   True  False       2
4      4     C  False   True       2
5      5   NaN   True  False       3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading