Fill down between rows in new dataframe column
Question:
I have a dataframe where I need to create a new column (Break
), and forward fill that column between all the Break
rows.
Type,Name
Parent,Parent1
Break,break010
Op,Op1
Unit,Unit1
Item,Item1
Break,break020
Op,Op2
Unit,Unit2
Break,break030
Op,Op3
Unit,Unit3
Parent,Parent2
Break,break010
For example, the output should be
Type Name Break
Parent Parent1
Break break010 break010
Op Op1 break010
Unit Unit1 break010
Item Item1 break010
Break break020 break020
Op Op2 break020
Unit Unit2 break020
Break break030 break030
Op Op3 break030
Unit Unit3 break030
Parent Parent2
Break break010 break010
Answers:
You can use DataFrame.where()
to replace values that are not "Break":
df["Break"] = df["Name"].where(df.Type == "Break", pd.NA).ffill().where(df.Type != "Parent", "")
This takes the "Name" column, and returns pd.NA
where the "Type" column is not "Break", then forward fills the values, and finally sets all columns where "Type" is "Parent" to ""
.
I have a dataframe where I need to create a new column (Break
), and forward fill that column between all the Break
rows.
Type,Name
Parent,Parent1
Break,break010
Op,Op1
Unit,Unit1
Item,Item1
Break,break020
Op,Op2
Unit,Unit2
Break,break030
Op,Op3
Unit,Unit3
Parent,Parent2
Break,break010
For example, the output should be
Type Name Break
Parent Parent1
Break break010 break010
Op Op1 break010
Unit Unit1 break010
Item Item1 break010
Break break020 break020
Op Op2 break020
Unit Unit2 break020
Break break030 break030
Op Op3 break030
Unit Unit3 break030
Parent Parent2
Break break010 break010
You can use DataFrame.where()
to replace values that are not "Break":
df["Break"] = df["Name"].where(df.Type == "Break", pd.NA).ffill().where(df.Type != "Parent", "")
This takes the "Name" column, and returns pd.NA
where the "Type" column is not "Break", then forward fills the values, and finally sets all columns where "Type" is "Parent" to ""
.