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
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
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