Search code examples
python-3.xpandasdataframemin

How to get the minimum time value in a dataframe with excluding specific value


I have a dataframe that has the format as below. I am looking to get the minimum time value for each column and save it in a list with excluding a specific time value with a format (00:00:00) to be a minimum value in any column in a dataframe.

df =  

    10.0.0.155  192.168.1.240   192.168.0.242

0    19:48:46      16:23:40      20:14:07

1    20:15:46      16:23:39      20:14:09

2    19:49:37      16:23:20      00:00:00

3    20:15:08      00:00:00      00:00:00

4    19:48:46      00:00:00      00:00:00

5    19:47:30      00:00:00      00:00:00

6    19:49:13      00:00:00      00:00:00

7    20:15:50      00:00:00      00:00:00

8    19:45:34      00:00:00      00:00:00

9    19:45:33      00:00:00      00:00:00

I tried to use the code below, but it doesn't work:

minValues = []

for column in df:

    #print(df[column])

    if "00:00:00" in df[column]:

        minValues.append (df[column].nlargest(2).iloc[-1])

    else:

        minValues.append (df[column].min()) 

print (df)     
   
print (minValues)

Solution

  • Idea is replace 0 to missing values and then get minimal timedeltas:

    df1 = df.astype(str).apply(pd.to_timedelta)
    
    s1 = df1.mask(df1.eq(pd.Timedelta(0))).min()
    print (s1)
    10.0.0.155      0 days 19:45:33
    192.168.1.240   0 days 16:23:20
    192.168.0.242   0 days 20:14:07
    dtype: timedelta64[ns]
    

    Or with get minimal datetimes and last convert output to HH:MM:SS values:

    df1 = df.astype(str).apply(pd.to_datetime)
    
    s2 = (df1.mask(df1.eq(pd.to_datetime("00:00:00"))).min().dt.strftime('%H:%M:%S')
    print (s2)
    10.0.0.155       19:45:33
    192.168.1.240    16:23:20
    192.168.0.242    20:14:07
    dtype: object
    

    Or to times:

    df1 = df.astype(str).apply(pd.to_datetime)
    
    s3 = df1.mask(df1.eq(pd.to_datetime("00:00:00"))).min().dt.time
    print (s3)
    10.0.0.155       19:45:33
    192.168.1.240    16:23:20
    192.168.0.242    20:14:07
    dtype: object