While iterating through the rows of a specific column in a Pandas DataFrame, I would like to add a new row below the currently iterated row, if the cell in the currently iterated row meets a certain condition.
Say for example:
df = pd.DataFrame(data = {'A': [0.15, 0.15, 0.7], 'B': [1500, 1500, 7000]})
DataFrame:
A B
0 0.15 1500
1 0.15 1500
2 0.70 7000
Attempt:
y = 100 #An example scalar
i = 1
for x in df['A']:
if x is not None: #Values in 'A' are filled atm, but not necessarily.
df.loc[i] = [None, x*y] #Should insert None into 'A', and product into 'B'.
df.index = df.index + 1 #Shift index? According to this S/O answer: https://stackoverflow.com/a/24284680/4909923
i = i + 1
df.sort_index(inplace=True) #Sort index?
I haven't been able to succeed so far; getting a shifted index numbering that doesn't start at 0, and rows seem not to be inserted in an orderly way:
A B
3 0.15 1500
4 NaN 70
5 0.70 7000
I tried various variants of this, trying to use applymap
with a lambda function, but was not able to get it working.
Desired result:
A B
0 0.15 1500
1 None 15
2 0.15 1500
3 None 15
4 0.70 7000
5 None 70