Skip to content
Advertisement

Create New Columns Using Multiple Conditions And Time Difference

I have the following dataframe with a tricky problem:

JavaScript

I have to make 4 columns (0-90 days, 91-180 days, 181-270 days, 271-360 days) based on the following conditions:

JavaScript

Desired output:

JavaScript

What would be the smartest way of doing it? Any suggestions would be appreciated. Thanks!

Advertisement

Answer

You can write a custom function that takes in a list of weights, start day, end day — then apply this function rowwise to create each of your new columns using the pandas apply function. If you haven’t used apply before, the basic structure is something like: df.apply(lambda x: custom_function(...), axis=1). The argument axis=1 ensures your custom function is applied rowwise.

Since the names of your new columns are also the start and end days, you can loop through these start and end day ranges.

Also I noticed that in your question there seem to be some mismatches between the DataFrame you created and your desired output, so I am taking the the desired output to be the DataFrame.

JavaScript

Output:

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