1

I am trying and failing here. All I want to do is take a "Time_of_Event" value from this dataframe:

events_data = {'Time_of_Event':[8, 22, 24,34,61,62,73,79,86]}
my_events_df = pd.DataFrame(events_data)

And search it against the "Job_Start_Times" of this dataframe:

job_data = {'Job_Start_Time':[20,50,75], 'Job_Name':['Job_01','Job_02','Job_03']}
my_jobs_df = pd.DataFrame(job_data)

And find which range it falls in, and return/append the "Job_Name" to my first "my_events_df" dataframe.

For example, for the value of 8 in "Time_of_Event", I want to return "Job_01". For the value of 61, I want to return "Job_02", as 61 falls between 50 and 75.

I've tried some for loops, if-elses, and I haven't made much progress. Any help is appreciated!

anky
  • 74,114
  • 11
  • 41
  • 70
Adm
  • 11
  • 3
  • I am not clear what you are asking what if it falls between 20 to 50,that is 24 is it `Job_01` or `Job_02` – Shubham Shaswat Feb 08 '20 at 16:14
  • 3
    Does this answer your question? [Python: Checking to which bin a value belongs](https://stackoverflow.com/questions/14947909/python-checking-to-which-bin-a-value-belongs) – AMC Feb 08 '20 at 16:34
  • can you please post the expected output dataframe similar to the way you've posted the input dataframes. that way it would be a lot clearer as to what you want. Specially when the bins doesnt overlap – anky Feb 08 '20 at 17:17

1 Answers1

1

We can try with pd.merge_asof

new_df = (pd.merge_asof(my_events_df.sort_values('Time_of_Event'),
                        my_jobs_df, left_on='Time_of_Event',
                        right_on = 'Job_Start_Time',
                        direction = 'backward')
  .drop(columns = 'Job_Start_Time')
  .bfill())
print(new_df)
   Time_of_Event Job_Name
0              8   Job_01
1             22   Job_01
2             24   Job_01
3             34   Job_01
4             61   Job_02
5             62   Job_02
6             73   Job_02
7             79   Job_03
8             86   Job_03
ansev
  • 30,322
  • 5
  • 17
  • 31
  • This is literally exactly what I was looking for... and I wouldn't have figured it out. I really appreciate the help! – Adm Feb 08 '20 at 19:15
  • You are wellcome:) please consider Accept my answer:) – ansev Feb 08 '20 at 19:33