vendredi 10 janvier 2020

How to keep decimals intact when copying values from previous row?

I have a df with a and indicator and I want to create 2 columns (a-1 and a-2) using values from another column and previous row conditionally, in a for-loop.

df:
a, indicator, a-1, a-2
20.456, 0, 0, 0
34.23, 0, 0, 0
52.5871, 1, 34.23, 20.456
27.265, 1, 52.5871, 34.23

I tried:

for i in range(1, len(df)):
  if df['indicator][i] == 1:
    count_neg=0
    j=1,
    count=0
    while count_neg < 2:

      if df['indicator][i] == 1:
        count=count+1
        count_neg=count_neg+1
        if count==1 and df['a'[i-j] is not None:
          df['a-1'][i] = df['a'][i-j] 
        if count==2 and df['a'[i-j] is not None:
          df['a-2'][i] = df['a'][i-j] 

      j=j+1

I am getting the values without the decimals:

df:
a, indicator, a-1, a-2
20.456, 0, 0, 0
34.23, 0, 0, 0
52.5871, 1, 34, 20
27.265, 1, 52, 34

Aucun commentaire:

Enregistrer un commentaire