Reputation: 69
I have a dataframe formatted like this in pandas.
Building ID Column 2 Column 3
Building 1 100 200
Building 2 201 302
Building 3 303 404
....
I want to be able to enter a value, and if the value is between the numbers in Column 2 and 3, I'd like to return the associated Building ID.
So my desired output would be like this
Input Number: 205
Building ID Column 2 Column 3
Building 2 201 302
or even just
Input Number: 205
Building ID
Building 2
I'm not sure if I need a conditional statement, or something along the lines of an inbetween function to get my desired results. Thanks
Upvotes: 1
Views: 217
Reputation: 1304
data.csv file:
Building ID,Column 2,Column 3
Building 1,100,200
Building 2,201,302
Building 3,303,404
code:
import numpy as np
import pandas as pd
df = pd.read_csv("data.csv")
print(df)
number = 205
newdf = df[(df['Column 2'] <= number) & (number <= df['Column 3'])]
print(newdf)
Upvotes: 0
Reputation: 16162
You can use between
by using df.loc
and having two conditions, one where the input_number
is greater than or equal to Column 2
and one where it is less than or equal to Column 3
df = pd.DataFrame({'Building ID': {0: 'Building 1', 1: 'Building 2', 2: 'Building 3'},
'Column 2': {0: 100, 1: 201, 2: 303},
'Column 3': {0: 200, 1: 302, 2: 404}})
input_number = int(input('Number'))
df.loc[(input_number >= df['Column 2']) & (input_number <= df['Column 3'])]
# or if you prefer the built in greater than less than methods:
# df.loc[(df['Column 2'].le(input_number)) & (df['Column 3'].ge(input_number))]
Output
Building ID Column 2 Column 3
1 Building 2 201 302
Upvotes: 1