logo
Tags down

shadow

Pandas dividing distance by timedelta


By : Ciaran O'Flynn
Date : October 17 2020, 08:10 PM
I hope this helps you . You can get the total seconds for the timedelta column, convert to hours, and divide:
code :
time = pd.to_timedelta(df.time_diff, errors='coerce').dt.total_seconds() / 3600
# If already timedelta, use
# time = df.time_diff.dt.total_seconds() / 3600
df['distance'] / time

0          NaN
1    10.987980
2    11.293138
3     9.802945
4    -3.132538
5          NaN
6          NaN
dtype: float64


Share : facebook icon twitter icon

timedelta csv pandas


By : Diego Lins
Date : March 29 2020, 07:55 AM
around this issue I didn't find any mentions about deltatime in pandas, and datetime module has one, so to convert D_Time to seconds is not bad idea:
code :
def seconds(time_str):
    end_time = datetime.datetime.strptime(time_str,'%H:%M:%S')
    delta = end_time - datetime.datetime.strptime('0:0:0','%H:%M:%S')
    return delta.total_seconds()


df_SOF1.D_Time = df_SOF1.D_Time.apply(seconds)
>>> df_SOF1.groupby('CostCentre').sum()
            Location  D_Time  count
CostCentre                         
0                 45   27180     69
2073             420  594660     21
timeit.timeit("sec('01:01:01')", setup="from __main__ import sec",
              number=10000)
1.025843858718872

timeit.timeit("seconds('01:01:01')", setup="from __main__ import seconds",
              number=10000)
0.6128969192504883 

Python timedelta object - strfdelta and deltafstr functions for conversion of timedelta string timedelta


By : Adrian Rumin
Date : March 29 2020, 07:55 AM
this one helps. After searching for such functions, and not being able to find one that converts back and forth, I wrote the following two functions and include them in a script. This is compatible with Python v2.6.6, which doesn't support some newer features such as timedelta.total_seconds():
code :
#!/usr/bin/python

import re
import sys
import datetime

# String from Date/Time Delta:
#  Takes a datetime.timedelta object, and converts the internal values
#  to a dd:HH:mm:ss:ffffff string, prefixed with "-" if the delta is
#  negative
def strfdelta(tdelta):

    # Handle Negative time deltas
    negativeSymbol = ""
    if tdelta < datetime.timedelta(0):
        negativeSymbol = "-"

    # Convert days to seconds, as individual components could
    # possibly both be negative
    tdSeconds = (tdelta.seconds) + (tdelta.days * 86400)

    # Capture +/- state of seconds for later user with milliseonds calculation
    secsNegMultiplier = 1
    if tdSeconds < 0:
        secsNegMultiplier = -1

    # Extract minutes from seconds
    tdMinutes, tdSeconds = divmod(abs(tdSeconds), 60)

    # Extract hours from minutes
    tdHours, tdMinutes = divmod(tdMinutes, 60)
    # Extract days from hours
    tdDays, tdHours = divmod(tdHours, 24)

    # Convert seconds to microseconds, as individual components 
    # could possibly both be negative
    tdMicroseconds = (tdelta.microseconds) + (tdSeconds * 1000000 * secsNegMultiplier)

    # Get seconds and microsecond components
    tdSeconds, tdMicroseconds = divmod( abs(tdMicroseconds), 1000000)

    return "{negSymbol}{days}:{hours:02d}:{minutes:02d}:{seconds:02d}:{microseconds:06d}".format(
        negSymbol=negativeSymbol,
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)


# Date/Time delta from string
# Example: -1:23:32:59:020030 (negative sign optional)
def deltafstr(stringDelta):

    # Regular expression to capture status change events, with groups for date/time, 
    #  instrument ID and state
    regex = re.compile("^(-?)(\d{1,6}):([01]?\d|2[0-3]):([0-5][0-9]):([0-5][0-9]):(\d{6})$",re.UNICODE)
    matchObj = regex.search(stringDelta)

    # If this line doesn't match, return None
    if(matchObj is None):
        return None;

    # Debug - Capture date-time from regular expression 
    # for g in range(0, 7):
    #     print "Grp {grp}: ".format(grp=g) + str(matchObj.group(g)) 

    # Get Seconds multiplier (-ve sign at start)
    secsNegMultiplier = 1
    if matchObj.group(1):
        secsNegMultiplier = -1

    # Get time components
    tdDays = int(matchObj.group(2)) * secsNegMultiplier
    tdHours = int(matchObj.group(3)) * secsNegMultiplier
    tdMinutes = int(matchObj.group(4)) * secsNegMultiplier
    tdSeconds = int(matchObj.group(5)) * secsNegMultiplier
    tdMicroseconds = int(matchObj.group(6)) * secsNegMultiplier

    # Prepare return timedelta
    retTimedelta = datetime.timedelta(
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)

    return retTimedelta;
# Testing (change the constructor for timedelta to test other cases)
firstDelta = datetime.timedelta(seconds=-1,microseconds=999999, days=-1)
print "--------"
print firstDelta
firstDeltaStr = strfdelta(firstDelta)
print "--------"
print firstDeltaStr;
secondDelta = deltafstr(firstDeltaStr)
print "--------"
print secondDelta
secondDeltaStr = strfdelta(secondDelta)
print "--------"
print secondDelta
print "--------"

How to work out speed from distance as a float and time as a timedelta


By : czernobog
Date : March 29 2020, 07:55 AM
wish help you to fix your issue If I have a distance in km float variable, and a timedelta variable of time, how can I work out speed in KM/H? I'm not sure how to change timedelta to hours as a float. An example would be: , convert that '1:04' to seconds
code :
distance = 0.966757

time = datetime.timedelta(0,64)

distance/time.total_seconds()
>>0.015105578125
3600*distance/time.total_seconds()
>>54.380081249999996
time.total_seconds() == time.seconds
>>True

How to convert great_circle distance to timedelta in Python?


By : Remus Curte
Date : March 29 2020, 07:55 AM
I wish this helpful for you I have used great_circle function to find the distance between two coordinates.For example, if i have the following data: , Consider using .km attribute.
Demo:
code :
In [33]: df
Out[33]:
    lat1   lon1     lat2   lon2
0 -77.85  80.23 -22.4532  62.45

In [34]: distance = x.apply(lambda x: great_circle((x['lat1'], x['lon1']),
                                                   (x['lat2'], x['lon2'])).km,
                                                   axis = 1)
#  ---->                                                                  ^^^

In [35]: distance
Out[35]:
0    6233.235674
dtype: float64

In [36]: df['time'] = pd.to_timedelta(distance/80,unit='h')

In [37]: df
Out[37]:
    lat1   lon1     lat2   lon2                   time
0 -77.85  80.23 -22.4532  62.45 3 days 05:54:55.605600

pandas.Timedelta with BusinessDay


By : MrCapable
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I need to apply a pd.Timedelta offset to an index but I would like to take into consideration only business days. Unfortunately this is not possible as pd.Timedelta doesn't support business days at the moment. , This is a possible solution:
code :
def add_bday_timedelta(input, timedelta):
    """
    Add timedelta to input taking into consideration business days
    """
    days = timedelta.components.days
    offset = timedelta - '%dD' % days
    return input + BusinessDay(days) + offset

>>> add_bday_timedelta(d, td)
DatetimeIndex(['2015-01-14 03:00:00', '2015-01-15 03:00:00',
               '2015-01-16 03:00:00', '2015-01-19 03:00:00',
               '2015-01-20 03:00:00', '2015-01-21 03:00:00',
               '2015-01-22 03:00:00', '2015-01-23 03:00:00',
               '2015-01-26 03:00:00'],
              dtype='datetime64[ns]', freq='B')
Related Posts Related Posts :
  • String Manipulation Recursive Function
  • Filter after Groupby and Sum in pandas?
  • writing a custom function Multiply the average of x,y
  • Spotify API fetch authorization code from redirect_uri
  • sklearn use RandomizedSearchCV with custom metrics and catch Exceptions
  • IndexOutOfRange error when filling a List Python
  • sns stripplot with just top n number of categories
  • Python classes keep calling eachother
  • How do I create a Dataframe_new in python from an existing Dataframe_old.
  • calculating an intercept point between a straight line and an ellipse - python
  • Integrating Tensorflow object detection with keras cnn classifier
  • How to skip comma while reading CSV file in python?
  • Stop Integrating when Output Reaches 0 in scipy.integrate.odeint
  • Changing the current graph of tf.placeholder objects in Tensorflow: Is it possible?
  • Logical error in while statement when used with or operator
  • django-rest-framework: int() argument must be a string, a bytes-like object or a number, not Deferred Attribute
  • how to remove a whitespace in a list in python?
  • How to reduce the number of row repetitions in a numpy array
  • Python: Dividing values of nested list with values with values of dictionary
  • Printing empty Pyramid
  • Python: How to save log file toSharePoint
  • Python Pandas count most frequent occurrences
  • How can I store / cache values from methods in a class for later use in other methods of the same class?
  • Sklearn: Pass class names to make_scorer
  • PyTorch - applying attention efficiently
  • How do I capitalize each parameter in a function definition using Python?
  • Regex matching of a bytes pattern gives unusual results - '.' not equivalent to [\x00-\xff]
  • I need help converting this REST API Curl command to Python requests
  • How do you make a variable comparison to decide a better score in a dice game?
  • How do I run sumo-gui on instant-veins-4.7.1-i1.ova
  • Deal with NAN values when creating models with python
  • Python requests: having a space in header for posting
  • Adding a column to a pandas dataframe based on cell values
  • Get mongod rs.status() results from a python script
  • ImportError: C extension: No module named 'parsing' not built
  • python pandas update column values related to previous updated row during iteration over it
  • 3 nested loops: Optimizing a simple simulation for speed
  • Assign subset of values to pandas dataframe with MultiIndex
  • How to group two sets of buttons on each top corner of the screen using Tkinter?
  • django login using class based for custom user
  • MRJob sort reducer output
  • Python Pandas Counts using rolling time window
  • Getting or editing a string from a column in a csv file with pandas
  • Python - Delete row in matrix/array if row contains
  • Using dicom Images with OpenCV in Python
  • Odoo ghost record
  • Creating and assigning multiple variables in a tkinter application
  • Graph dictionary
  • No changes to original dataframe after applying loop
  • AUC of Random forest model is lower after tuning parameters using hypergrid search and CV with 10 folds
  • Python: Reading multiple CSV files, and assigning each to a different variable
  • How to identify empty rectangle using OpenCV
  • How to iterate multilevel dataframe in python
  • How to limit the contour plot with a line plot?
  • Why subclassing a str or int behaves differently from subclising a list or dict?
  • Python decode with translation table
  • i need to click unordered links in the below URL using selenium, python
  • How to join pandas dataframe with itself?
  • How to apply a color cast to a video frame in OpenCV Python?
  • Is there any existing library for median filtering with kernel size greater then 5 using OpenCL acceleration in python?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org