Recommand · November 24, 2021 0

How do I add 0 rows under certain conditions?

I have a pandas.DataFrame of the form

df=

  index   ID     A       B
    
    0      a     0       111
    1      a     1       111
    2      a     2       111
    3      b     3       111
    4      c     0       111
    5      c     2       111
    6      c     3       111
    7      d     0       111
    8      d     1       111
    9      e     2       111
    10     f     1       111
    11     f     2       111
    12     f     3       111
    13     g     1       111
    14     g     2       111

I want to create a dataframe in which column A repeats 0,1,2,3. But there is something missing in the data. I’m trying to fill in the blanks with 0 by appending row values. Here is my expected result:

   index   ID     A       B
    
    0      a     0       111
    1      a     1       111
    2      a     2       111
    3      a     3       0
    4      b     0       0
    5      b     1       0
    6      b     2       0
    7      b     3       111
    8      c     0       111
    9      c     1       0
    10     c     2       111
    11     c     3       111
    12     d     0       111
    13     d     1       111
    14     d     2       0
    15     d     3       0
    16     e     0       0
    17     e     1       0
    18     e     2       111
    19     e     3       0
    20     f     0       0
    21     f     1       111
    22     f     2       111
    23     f     3       111
    24     g     0       0
    25     g     1       111
    26     g     2       111
    27     g     3       0

Or you can do something like below. Perhaps it will be easier.

  index   ID     A       B
    
    0      a     0       111
    1      a     1       111
    2      a     2       111
    3      0     3       0
    4      0     0       0
    5      0     1       0
    6      0     2       0
    7      b     3       111
    8      c     0       111
    9      0     1       0
    10     c     2       111
    11     c     3       111
    12     d     0       111
    13     d     1       111
    14     0     2       0
    15     0     3       0
    16     0     0       0
    17     0     1       0
    18     e     2       111
    19     0     3       0
    20     0     0       0
    21     f     1       111
    22     f     2       111
    23     f     3       111
    24     0     0       0
    25     g     1       111
    26     g     2       111
    27     0     3       0

How can I achieve this?

too difficult. What should I do?. I used .diff().le(0) when changing from a large number to a small number, such as changing from ID(b) to ID(c). However, when changing from a small number to a large number, such as changing from ID(a) to ID(b) or ID(d) to ID(e), it could not be solved.