简体   繁体   中英

Python Pandas Counting and Summing columns based on datetime values

I am trying to count up values if they meet a certain condition and store it in another column, (I want to check how many Tickets are open at the same time as another ticket) Submit date & resolved date are columns looking like this

df['Submit_Date']  = 
  1   10/1/16 23:41
  2   10/1/16 23:50
  3  10/2/16 0:05
  4   10/3/16 5:17

df['Resolved_Date'] = 
  1  10/2/16 2:27
  2  3/9/17 19:39
  3  11/15/16 12:46
  4  11/14/16 17:37

I would like to look at row 2 and see which of the other 3 times were open during any of the same time as row 2 So this answer would be row 1, row 3, and row 4 as they all have submit dates or resolved dates that fall between Oct 2, 2016 and March 9,2017
I want to do this for every row though, and scan through all the other columns

Here is what I have so far

df['newcolumn'] = ((df['Submit_Date'] < df['Submit_Date']) |   (df['Resolved_Date'] > df['Resolved_Date'])).sum()

The problem is I want to check if the submit date in that current row is greater than all the other rows and the resolved date in that row is less than all the other rows. I want to find all the values that match this criteria for each row and save it in the same row in a new column

You would have to loop across the dataframe as you have to compare each row with every other row. One improvement can be there in the below solution is by sorting by Submit_Date such that you have to compare with either below that record or above that record for the submit_date comparison.

result = list()
for row in df.iterrows():
    cur_data = row[1]
    result.append((((cur_data['Submit_Date'] < df['Submit_Date']) & (df['Submit_Date']< cur_data['Resolved_Date']))
                  | ((cur_data['Submit_Date'] < df['Resolved_Date']) & (df['Resolved_Date'] < cur_data['Resolved_Date']))).sum())
df['count'] = result


         Submit_Date       Resolved_Date    count
1   2016-10-01 23:41:00 2016-10-02 02:27:00 2
2   2016-10-01 23:50:00 2017-03-09 19:39:00 3
3   2016-10-02 00:05:00 2016-11-15 12:46:00 2
4   2016-10-03 05:17:00 2016-11-14 17:37:00 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM