0

I'm new to Python, so I'm still learning. However, I'm trying to find the average, min and max from a text file that contains wind reading. I've got it to work, however, I need to convert NumPy to float, and I'm not sure how I do that.

import numpy as np

def main():
    text_file = open("tall_filtrert.txt", "r")

    total = 0.0

    count = 0

    print("Press enter to start")

    for line in text_file:
        run_time = float(line)

        count += 1

        total += run_time

    text_file.close()

    x = np.loadtxt("tall_filtrert.txt")
    print("There are", count, "")
    print('Average:', np.average(x))
    print('Max:', np.amax(x))
    print('Min:', np.amin(x))

main()

The code is slow, but there's like 800k readings. Any suggestions on how to improve the speed would help.

The text file goes something like this:

1.2056

1.3426

1.8632

etc.

Ben
  • 79
  • 8
  • `loadtxt` function has the default dtype as `float`. I do not get which part you want to convert to float ? – Koralp Catalsakal Jan 29 '20 at 13:10
  • @KoralpCatalsakal If I understand it correctly, when the numpy prints the average, max and min, it isn't a float? I've might be wrong on that? – Ben Jan 29 '20 at 13:11
  • In that case, you can use `astype()` function. `np.amin(list).astype(float)` – Koralp Catalsakal Jan 29 '20 at 13:13
  • @KoralpCatalsakal can you explain where I need to put that into the code? I'm new to numpy and python, so sorry if it sounds kinda dumb. – Ben Jan 29 '20 at 13:17

2 Answers2

2

You can check for the type of an instance (like a variable) with

y = 12.0
isinstance(y, float)

This is along the lines of Check if a number is int or float

And as @Florian H mentioned, if your text file only contains one column of numbers (a single number each line) the numpy array read by loadtxt will consist only of floats, so you will be fine.

B--rian
  • 5,578
  • 10
  • 38
  • 89
1

You can't convert a numpy array to a float (except it has only one value) because as its name says it is an array. Array means something like a sequence of floats. That basically would mean you try to convert multiple numbers into a single number.

The values itself on the othe hand should be float allready when you read them with loadtxt like @KoralpCatalsakal mentioned.

the return values of np.average, np.max and np.min should also be floats.

To you speed problem: Read your file only once.

def main():
    x = np.loadtxt("tall_filtrert.txt")
    print("There are", len(x), "")
    print('Average:', np.average(x))
    print('Max:', np.max(x))
    print('Min:', np.min(x))

main()

If you need the sum of your values go with:

total = np.sum(x)
Florian H
  • 3,052
  • 2
  • 14
  • 25