Iterating over time series2019 Community Moderator ElectionCalculate relative time in C#How do I iterate over a range of numbers defined by variables in Bash?How to get the current time in PythonWhy is using “for…in” with array iteration a bad idea?How can I make a time delay in Python?What do 'real', 'user' and 'sys' mean in the output of time(1)?A 'for' loop to iterate over an enum in JavaIterating over dictionaries using 'for' loopsHow to iterate over rows in a DataFrame in Pandas?Why are some float < integer comparisons four times slower than others?

Automaton recognizing ambiguously accepted words of another automaton

Are all players supposed to be able to see each others' character sheets?

ESPP--any reason not to go all in?

What is this tube in a jet engine's air intake?

How can I portion out frozen cookie dough?

When an outsider describes family relationships, which point of view are they using?

Has a sovereign Communist government ever run, and conceded loss, on a fair election?

Short scifi story where reproductive organs are converted to produce "materials", pregnant protagonist is "found fit" to be a mother

Smooth vector fields on a surface modulo diffeomorphisms

Cycles on the torus

Would those living in a "perfect society" not understand satire

PTIJ: Sport in the Torah

I am the person who abides by rules, but breaks the rules. Who am I?

Do black holes violate the conservation of mass?

Use Mercury as quenching liquid for swords?

Difference between `nmap local-IP-address` and `nmap localhost`

What does the Digital Threat scope actually do?

-1 to the power of a irrational number

What can I do if someone tampers with my SSH public key?

Too soon for a plot twist?

How to educate team mate to take screenshots for bugs with out unwanted stuff

Did Amazon pay $0 in taxes last year?

"If + would" conditional in present perfect tense

Does an unused member variable take up memory?



Iterating over time series



2019 Community Moderator ElectionCalculate relative time in C#How do I iterate over a range of numbers defined by variables in Bash?How to get the current time in PythonWhy is using “for…in” with array iteration a bad idea?How can I make a time delay in Python?What do 'real', 'user' and 'sys' mean in the output of time(1)?A 'for' loop to iterate over an enum in JavaIterating over dictionaries using 'for' loopsHow to iterate over rows in a DataFrame in Pandas?Why are some float < integer comparisons four times slower than others?










2















The following is a sample of my dataset:





index time speed
0 00:00:00 15
1 00:00:05 18
2 00:00:10 23
3 00:00:15 25
4 00:00:20 34


I would like to create a for loop that does the same function as below:





for i in range (0,5,1):
if df.speed[i] > df.speed [i+2]:
print ('Larger')
else:
print('Smaller')


However, I would like to refer to time instead of indices in the FOR loop. For example:





for t in range (00:00:00, 00:00:20 , 5s):
if df.speed[t] > df.speed [t+10s]:
print ('Larger')
else:
print('Smaller')


So the FOR LOOP will take the speed value at a certain t and compare with it the value of the speed after 10 seconds. If it is larger, then it prints Larger, otherwise, Smaller.



I appreciate any help. Thanks.










share|improve this question









New contributor




Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    2















    The following is a sample of my dataset:





    index time speed
    0 00:00:00 15
    1 00:00:05 18
    2 00:00:10 23
    3 00:00:15 25
    4 00:00:20 34


    I would like to create a for loop that does the same function as below:





    for i in range (0,5,1):
    if df.speed[i] > df.speed [i+2]:
    print ('Larger')
    else:
    print('Smaller')


    However, I would like to refer to time instead of indices in the FOR loop. For example:





    for t in range (00:00:00, 00:00:20 , 5s):
    if df.speed[t] > df.speed [t+10s]:
    print ('Larger')
    else:
    print('Smaller')


    So the FOR LOOP will take the speed value at a certain t and compare with it the value of the speed after 10 seconds. If it is larger, then it prints Larger, otherwise, Smaller.



    I appreciate any help. Thanks.










    share|improve this question









    New contributor




    Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      2












      2








      2








      The following is a sample of my dataset:





      index time speed
      0 00:00:00 15
      1 00:00:05 18
      2 00:00:10 23
      3 00:00:15 25
      4 00:00:20 34


      I would like to create a for loop that does the same function as below:





      for i in range (0,5,1):
      if df.speed[i] > df.speed [i+2]:
      print ('Larger')
      else:
      print('Smaller')


      However, I would like to refer to time instead of indices in the FOR loop. For example:





      for t in range (00:00:00, 00:00:20 , 5s):
      if df.speed[t] > df.speed [t+10s]:
      print ('Larger')
      else:
      print('Smaller')


      So the FOR LOOP will take the speed value at a certain t and compare with it the value of the speed after 10 seconds. If it is larger, then it prints Larger, otherwise, Smaller.



      I appreciate any help. Thanks.










      share|improve this question









      New contributor




      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      The following is a sample of my dataset:





      index time speed
      0 00:00:00 15
      1 00:00:05 18
      2 00:00:10 23
      3 00:00:15 25
      4 00:00:20 34


      I would like to create a for loop that does the same function as below:





      for i in range (0,5,1):
      if df.speed[i] > df.speed [i+2]:
      print ('Larger')
      else:
      print('Smaller')


      However, I would like to refer to time instead of indices in the FOR loop. For example:





      for t in range (00:00:00, 00:00:20 , 5s):
      if df.speed[t] > df.speed [t+10s]:
      print ('Larger')
      else:
      print('Smaller')


      So the FOR LOOP will take the speed value at a certain t and compare with it the value of the speed after 10 seconds. If it is larger, then it prints Larger, otherwise, Smaller.



      I appreciate any help. Thanks.







      python for-loop if-statement time jupyter






      share|improve this question









      New contributor




      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 4 hours ago







      Alex Davies













      New contributor




      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Mar 6 at 21:30









      Alex DaviesAlex Davies

      235




      235




      New contributor




      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Alex Davies is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Date Range (Seconds)



          It seems you're using pandas. If that's so, you really should look at it's Time Series features: https://pandas.pydata.org/pandas-docs/stable/timeseries.html



          More specific, at pandas.date_range():



          import pandas as pd

          pd.date_range('00:00:00', '00:00:20', freq='5s')


          Since it's a date range function, it'll return datetimes



          DatetimeIndex(['2019-03-06 00:00:00',
          '2019-03-06 00:00:05',
          ...,
          '2019-03-06 00:00:20'], dtype='datetime64[ns]', freq='5S')


          From here just use .strftime() to get what you want:



          pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S')



          Returns



          Index(['00:00:00', '00:00:05', ..., '00:00:20'], dtype='object')




          Access dataframe by time



          After that, in order to access your dataframe using this index you have two options:



          1. Using .loc to find the row where this time is:

          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.loc[df['time'] == time, 'speed'] ..):


          1. By redefining the dataframe index with set_index(), and then accessing it directly by time:

          df.set_index('time', inplace=True)
          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.speed[time] ...):



          Edit to address comment question



          After you you use strftime() it is converted to a String. You could convert it back to add the 10 seconds like:



          df.speed[(pd.to_datetime(time) + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')].



          Or:



          for time in pd.date_range('00:00:00', '00:00:20', freq='5s'):
          if (df.speed[time.strftime('%H:%M:%S')]>df.speed[(time + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')]):





          share|improve this answer










          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.




















          • Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

            – Alex Davies
            2 days ago







          • 1





            Added an edit to address this.

            – jmiguel
            2 days ago










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          Alex Davies is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55032453%2fiterating-over-time-series%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Date Range (Seconds)



          It seems you're using pandas. If that's so, you really should look at it's Time Series features: https://pandas.pydata.org/pandas-docs/stable/timeseries.html



          More specific, at pandas.date_range():



          import pandas as pd

          pd.date_range('00:00:00', '00:00:20', freq='5s')


          Since it's a date range function, it'll return datetimes



          DatetimeIndex(['2019-03-06 00:00:00',
          '2019-03-06 00:00:05',
          ...,
          '2019-03-06 00:00:20'], dtype='datetime64[ns]', freq='5S')


          From here just use .strftime() to get what you want:



          pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S')



          Returns



          Index(['00:00:00', '00:00:05', ..., '00:00:20'], dtype='object')




          Access dataframe by time



          After that, in order to access your dataframe using this index you have two options:



          1. Using .loc to find the row where this time is:

          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.loc[df['time'] == time, 'speed'] ..):


          1. By redefining the dataframe index with set_index(), and then accessing it directly by time:

          df.set_index('time', inplace=True)
          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.speed[time] ...):



          Edit to address comment question



          After you you use strftime() it is converted to a String. You could convert it back to add the 10 seconds like:



          df.speed[(pd.to_datetime(time) + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')].



          Or:



          for time in pd.date_range('00:00:00', '00:00:20', freq='5s'):
          if (df.speed[time.strftime('%H:%M:%S')]>df.speed[(time + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')]):





          share|improve this answer










          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.




















          • Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

            – Alex Davies
            2 days ago







          • 1





            Added an edit to address this.

            – jmiguel
            2 days ago















          1














          Date Range (Seconds)



          It seems you're using pandas. If that's so, you really should look at it's Time Series features: https://pandas.pydata.org/pandas-docs/stable/timeseries.html



          More specific, at pandas.date_range():



          import pandas as pd

          pd.date_range('00:00:00', '00:00:20', freq='5s')


          Since it's a date range function, it'll return datetimes



          DatetimeIndex(['2019-03-06 00:00:00',
          '2019-03-06 00:00:05',
          ...,
          '2019-03-06 00:00:20'], dtype='datetime64[ns]', freq='5S')


          From here just use .strftime() to get what you want:



          pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S')



          Returns



          Index(['00:00:00', '00:00:05', ..., '00:00:20'], dtype='object')




          Access dataframe by time



          After that, in order to access your dataframe using this index you have two options:



          1. Using .loc to find the row where this time is:

          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.loc[df['time'] == time, 'speed'] ..):


          1. By redefining the dataframe index with set_index(), and then accessing it directly by time:

          df.set_index('time', inplace=True)
          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.speed[time] ...):



          Edit to address comment question



          After you you use strftime() it is converted to a String. You could convert it back to add the 10 seconds like:



          df.speed[(pd.to_datetime(time) + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')].



          Or:



          for time in pd.date_range('00:00:00', '00:00:20', freq='5s'):
          if (df.speed[time.strftime('%H:%M:%S')]>df.speed[(time + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')]):





          share|improve this answer










          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.




















          • Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

            – Alex Davies
            2 days ago







          • 1





            Added an edit to address this.

            – jmiguel
            2 days ago













          1












          1








          1







          Date Range (Seconds)



          It seems you're using pandas. If that's so, you really should look at it's Time Series features: https://pandas.pydata.org/pandas-docs/stable/timeseries.html



          More specific, at pandas.date_range():



          import pandas as pd

          pd.date_range('00:00:00', '00:00:20', freq='5s')


          Since it's a date range function, it'll return datetimes



          DatetimeIndex(['2019-03-06 00:00:00',
          '2019-03-06 00:00:05',
          ...,
          '2019-03-06 00:00:20'], dtype='datetime64[ns]', freq='5S')


          From here just use .strftime() to get what you want:



          pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S')



          Returns



          Index(['00:00:00', '00:00:05', ..., '00:00:20'], dtype='object')




          Access dataframe by time



          After that, in order to access your dataframe using this index you have two options:



          1. Using .loc to find the row where this time is:

          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.loc[df['time'] == time, 'speed'] ..):


          1. By redefining the dataframe index with set_index(), and then accessing it directly by time:

          df.set_index('time', inplace=True)
          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.speed[time] ...):



          Edit to address comment question



          After you you use strftime() it is converted to a String. You could convert it back to add the 10 seconds like:



          df.speed[(pd.to_datetime(time) + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')].



          Or:



          for time in pd.date_range('00:00:00', '00:00:20', freq='5s'):
          if (df.speed[time.strftime('%H:%M:%S')]>df.speed[(time + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')]):





          share|improve this answer










          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.










          Date Range (Seconds)



          It seems you're using pandas. If that's so, you really should look at it's Time Series features: https://pandas.pydata.org/pandas-docs/stable/timeseries.html



          More specific, at pandas.date_range():



          import pandas as pd

          pd.date_range('00:00:00', '00:00:20', freq='5s')


          Since it's a date range function, it'll return datetimes



          DatetimeIndex(['2019-03-06 00:00:00',
          '2019-03-06 00:00:05',
          ...,
          '2019-03-06 00:00:20'], dtype='datetime64[ns]', freq='5S')


          From here just use .strftime() to get what you want:



          pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S')



          Returns



          Index(['00:00:00', '00:00:05', ..., '00:00:20'], dtype='object')




          Access dataframe by time



          After that, in order to access your dataframe using this index you have two options:



          1. Using .loc to find the row where this time is:

          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.loc[df['time'] == time, 'speed'] ..):


          1. By redefining the dataframe index with set_index(), and then accessing it directly by time:

          df.set_index('time', inplace=True)
          for time in pd.date_range('00:00:00', '00:00:20', freq='5s').strftime('%H:%M:%S'):
          if (df.speed[time] ...):



          Edit to address comment question



          After you you use strftime() it is converted to a String. You could convert it back to add the 10 seconds like:



          df.speed[(pd.to_datetime(time) + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')].



          Or:



          for time in pd.date_range('00:00:00', '00:00:20', freq='5s'):
          if (df.speed[time.strftime('%H:%M:%S')]>df.speed[(time + pd.to_timedelta(10, unit='s')).strftime('%H:%M:%S')]):






          share|improve this answer










          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer








          edited 2 days ago





















          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered 2 days ago









          jmigueljmiguel

          1663




          1663




          New contributor




          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          jmiguel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.












          • Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

            – Alex Davies
            2 days ago







          • 1





            Added an edit to address this.

            – jmiguel
            2 days ago

















          • Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

            – Alex Davies
            2 days ago







          • 1





            Added an edit to address this.

            – jmiguel
            2 days ago
















          Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

          – Alex Davies
          2 days ago






          Thanks for your answer. However, there is one more point I would like to know for the if condition how to add or remove seconds on the time. for example: if (df.speed[time]>df.speed[time+ 10]) or should it be (+00:00:10), or (+'10s')?

          – Alex Davies
          2 days ago





          1




          1





          Added an edit to address this.

          – jmiguel
          2 days ago





          Added an edit to address this.

          – jmiguel
          2 days ago












          Alex Davies is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          Alex Davies is a new contributor. Be nice, and check out our Code of Conduct.












          Alex Davies is a new contributor. Be nice, and check out our Code of Conduct.











          Alex Davies is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55032453%2fiterating-over-time-series%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

          List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229