pythoninteger

Get only the integer from a numpy array


I'm working with data, I have phi, lambda, and Z, looks like this:

18.49528 88.29922 2.955
19.24444 103.70188 528.784
24.79509 107.41260 36.138
24.80513 107.40091 33.336

I read the file, and then extract the data using names

import numpy as np
file=np.loadtxt('data.txt')
phi=file[:,0]
lambda=file[:,1]
Z=file[:,2]

but then I have to solve some equations, and in one factor, I should have only the part integer from lambda so I did this

for i in lambda:
    print(int(i))
    A=(int(i))

when I print int(i) I get only the part integer, but when I want to save it in a variable, this only save one value, and I want all the values of lambda but only the part integer, how could I fix it?


Solution

  • I believe you are trying to store all integer part from the lambda list into a separate variable. What you're doing wrong is you are just storing the int(i) values to A and modifying it in every iteration instead of storing it into a collection like a list or a tuple.

    Here's how you can fix it:

    lambda_integers = []
    for i in lambda_vals:
        print(int(i))
        lambda_integers.append(int(i))
    

    Also, please refrain from using lambda as a variable name. It can conflict with the Python keyword lambda and as a good practice you should avoid giving such variable names. I have replaced lambda with lambda_vals.

    You can also use list comprehension to achieve your purpose:

    lambda_integers = [int(i) for i in lambda_vals]
    

    Hope that helps.