This is an example of my df:
pd.DataFrame([["1", "2"], ["1", "2"], ["3", "other_value"]],
columns=["a", "b"])
a b
0 1 2
1 1 2
2 3 other_value
And I want to arrive to this:
pd.DataFrame([["1", "2"], ["1", "2"], ["3", "other_value"], ["3", "row_duplicated_with_edits_in_this_column"]],
columns=["a", "b"])
a b
0 1 2
1 1 2
2 3 other_value
3 3 row_duplicated_with_edits_in_this_column
The rule is to use the apply method, do some checks (to keep the example simple I'm not including these checks), but under certain conditions, for some rows in the apply function, duplicate the row, make an edit to the row and insert both rows in the df.
So something like:
def f(row):
if condition:
row["a"] = 3
elif condition:
row["a"] = 4
elif condition:
row_duplicated = row.copy()
row_duplicated["a"] = 5 # I need also this row to be included in the df
return row
df.apply(f, axis=1)
I don't want to store the duplicated rows somewhere in my class and add them at the end. I want to do it on the fly.
I've seen this pandas: apply function to DataFrame that can return multiple rows but I'm unsure if groupby can help me here.
Thanks