0

I am trying to iterate a DataFrame rows with a if condition and add a new row right after whichever match the condition

for (index,row) in T.iterrows():
   if xxxx:
      ## add a new row right after current row
Yuan JI
  • 2,927
  • 2
  • 20
  • 29
  • [Please do NOT user iterrows to iterate over a pandas dataframe.](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas/55557758#55557758) – cs95 Jun 05 '19 at 13:37
  • in addition to that there is no order you could count on – user3732793 Jun 05 '19 at 13:41

1 Answers1

0

You could do it but it is slow, appreciate if anyone comes with a better solution.

    a       b
0   0.75    2.0
1   0.25    2.5
2   0.25    1.0
3   0.75    1.5
4   0.75    3.0
5   0.25    3.5
rows = []
for i, r in df.iterrows():
    rows.append(r)
    # let's b > 2 is the condition
    if r['b'] > 2:
        rows.append(pd.Series({'a': 1, 'b': 0}))
pd.DataFrame(rows).reset_index(drop=True)
    a       b
0   0.75    2.0
1   0.25    2.5
2   1.00    0.0
3   0.25    1.0
4   0.75    1.5
5   0.75    3.0
6   1.00    0.0
7   0.25    3.5
8   1.00    0.0
Yuan JI
  • 2,927
  • 2
  • 20
  • 29