-2

I have a list:

[1, 3 ,5, 7, NaN, NaN, NaN, 15, NaN]

I also have growth rate, let’s say it is : 0.5 .

I want my list to be filled with last number before NaN multiplied by 0.5 + 1. It’s is basically ffil * 1.5. But I don’t understand how to turn that into python code.

Can someone help?

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

Here:

import math
data = [1, 3 ,5, 7, float("NaN"), float("NaN"), float("NaN"), 15, float("NaN")]

growRate = 0.5

for i in range(len(data)):
    if math.isnan(float(data[i])):
        data[i] = data[i-1] * (growRate + 1)

print(data)
martineau
  • 119,623
  • 25
  • 170
  • 301
Cyber
  • 164
  • 7
  • `Nan` is a valid `float` value, so `float('NaN') == "NaN"` → `False`. Otherwise I think you have the right idea. – martineau Oct 07 '18 at 18:05
  • In a list you can't have letters without "", so I think that's the problem, or do you need to calculate the grow rate based on the Nan, or the difference between Nan and 7 in this case? – Cyber Oct 07 '18 at 18:10
  • We don't know the list was created as a source code literal. It might have been calculated at execution time. In general you could have a list of values with one or more having a `float` value of `Nan`. For example: `['a', 42, 3.14, float("NaN")]` → `['a', 42, 3.14, nan]`. Not that the `nan` at the end does not have quotes around it and isn't a string. – martineau Oct 07 '18 at 18:13
  • I didn't know about that, so then in this case `['a', 42, 3.14, nan]` you need to calculate the value of nan as a float? – Cyber Oct 07 '18 at 18:23
  • Not sure I understand your last comment. What I mean is your code should be `if data[i] == float("NaN"):` (and each "NaN" in `data` should be `float("NaN")` as well to create proper test values). – martineau Oct 07 '18 at 18:25
  • Sorry for my English it's not my native language but I'm trying. Ok I understand you now. – Cyber Oct 07 '18 at 18:27
  • No worries—your Python language skills seen quite good. `;¬)`. Fix your answer and I'll upvote it. Note you could also use `if math.isnan(data[i]):`. – martineau Oct 07 '18 at 18:29
  • Thank you for your help! – Nikita Polovinkin Oct 07 '18 at 21:04
0

I would suggest you going through What topics can I ask about here? first.

For your answer:

import math
NaN = float('nan')
growth_rate = 1.5
list_ = [1,3,5,7,NaN,NaN,NaN,15,NaN]
for i in range(0,len(list_)):
  if( math.isnan( list_[i] ) ): # True if list_[i] is NaN .
    list_[i] = growth_rate * list_[i-1]
for i in list_:
  print i ,

How can I check for NaN in Python?

  • It runs successfully! The conditional `if( math.isnan( float( list_[i] ) ) )`checks for `'nan'` after the element is casted to floating type as I think it should be. –  Oct 07 '18 at 19:09
  • Apparently you have fixed the problem since (and likely due to) my previous comment—so it now looks like it would work. – martineau Oct 07 '18 at 19:24