Search code examples
pandasdataframeloopsfor-loopchronological

How to chronological write values in column


Im new to Python so please excuse me if my code and logic isn't the best. Gotta start somewhere :)

im having trouble chronological writing values in a new column of a dataframe.

If the current and next value of _cycletime stay the same the counter stays as is it. If the current and next value of _cycletime are not the same the counter is increased by one.

Afterwards I'm trying to write the values of p in a new column named _cyclenumber.

p=1
for i in range((len(df81))-2):
     if   (df81['_cycletime'].iloc[i] == df81['_cycletime'].iloc[i+1]):
          p=p 
     elif (df81['_cycletime'].iloc[i] != df81['_cycletime'].iloc[i+1]):
          p+=1 
df81['_cyclenumber'] =  p  

exemplary excerpt from df81:

Index _time _power _cycletime
1 2022-07-30T11:00:28.042Z 12 55.4379997253
2 2022-07-30T11:00:28.554Z 10 55.4379997253
3 2022-07-30T11:00:29.068Z 11.5 55.4119987488
4 2022-07-30T11:00:29.623Z 8 55.4119987488

But instead of a chronological list I only get the same value in every cell:

Output I get vs Output I need

The number 64 comes from the amount of different cycletimes in the timeframe which is correct.

Thank you very much!!


Solution

  • uniques = df['_cycletime'].unique().tolist()
    df['_cyclenumber'] = df['_cycletime'].map(lambda x: uniques.index(x) + 1)
    

    your manner (corrected, don't recommended):

    p = 1
    df.loc[0, "_cyclenumber"] = p
    for i in range(1, len(df)):
        if df['_cycletime'].iloc[i] != df['_cycletime'].iloc[i-1]:
            p+=1 
        df.loc[i, "_cyclenumber"] = p