Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - Searching a range of a float

I am super new to python and am learning as I go. I have run into a problem. I need to search for a float in a dataframe column and return a dataframe that is sorted by the float. If the float is not in the dataframe I want it to search for a range of -.100 below the given float and +.200 above the given float. If found I want to return a sorted dataframe.

I tried the np.arage() function but I am getting:
ValueError: ('Lengths must match to compare', (2,), (300,))

Here is what I have so far.

import numpy as np
import pandas as pd

data = [[8,.125],[2,.375],[4,.625],[2,.188],[6,.625],[4,.500],[9,.312]]

df = pd.DataFrame(data, columns= ['Size','WT'])

print(df)

wt = float(input("Thickness to three decimals ---> "))
wtmin = wt - .100
wtmax = wt + .200
wtrange = np.arange(wtmin, wtmax, .010)

wtdf = df.loc[df['WT'] == WT]
    if wtdf.empty:
        wtdf = df.loc[df['WT'] == wtrange]
        print(wtdf)
    else:
        print(wtdf)  

If I input a known float the code works. If not I get the error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using the following statement to check the range instead of arange:

wtdf = df.loc[df['WT'] == wt]
    if wtdf.empty:
        wtdf = df.loc[wt - .1 < df['WT'] < wt + .2].sort_values('WT')
        print(wtdf)
    else:
        print(wtdf) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...