Skip to content
Advertisement

Pandas: Check each row for condition and insert row below if condition is met

this is my first question here as I really couldn’t figure it out with related answers: I have a list of dataframes “df_list”, for each user I have a dataframe which basically looks like:

JavaScript

Data:

JavaScript

I would like to go through all the dataframes in my df_list and inside each df I would like to add 1 row (below) where the ‘check’ value is > 15 hours.

Desired Output

JavaScript

Attempt:

So what I tried is to go with a for-loop into the list and there with another loop through all my rows in each dataframe. Then I checked via if-clause for my condition… I create a new blank line with the required index and then concat the dataframe so i can include the empty line.

JavaScript

I also found this here Add empty row if a condition is met Pandas but I can’t get this running as well…

JavaScript

In the next step I want to add the ‘Timestamp’ value from previous line + or – 10 hours, depending on the ‘value’ of the in/out column…but I thought I should figure out one problem at a time…

Advertisement

Answer

You can create a boolean mask using “check” column and add a row using Index.repeat and reindexing. Then sort_index and delete duplicate values:

JavaScript

Note that this assumes “check” is dtype timedelta object.

Output:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement