Python Forum

Full Version: Basic help with a dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone, I am just running a loop through a data frame. Here is an example of it.

Output:
{'NQ': Date High Low Close MA_50 Return 20210507 09:54:00 13742.50 13729.00 13729.25 13718.226 0.0 20210507 09:54:30 13732.25 13712.25 13716.75 13718.160 0.0
My dataframe is called NQ, and the index is Date with High, Low, Close, MA_50, and Return being columns.

So I am looping through. I know how to do if the current row high is greater then previous row high, print "Hello". I know how to have the loop "access" the columns.

But what if I want my loop to do something based on the index? Like if the timestamp is greater then 09:54:00 than "do something"?

How would I do that?

Heres an example of how I am just accessing the columns.. obviously I have renamed the DF.. but just showing you the simplicity of the code.

if esFutures[ticker]["High"][i] <= esFutures[ticker]["High"][i-1]:
Hmm no one has any idea how to access the timestamp in a dataframe??
(May-21-2021, 05:49 PM)stylingpat Wrote: [ -> ]Hmm no one has any idea how to access the timestamp in a dataframe??

look at this simple example

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'))
# shift target column by one index, in this way You avoid useless loop (look that obviously the first new row will be Nan)
df['A_shifted'] = df.A.shift(1)
# apply a function conditionally to "df.A_shifted <= df.A", where condition is not satisfied you can pass a default value as you want
df['result'] = np.select([df.A_shifted <= df.A], [df.A_shifted.apply(lambda x: x * 10)], default=df.A)