Home > Software design >  Numbers Between 2 Columns of Integers | Python Data Frame
Numbers Between 2 Columns of Integers | Python Data Frame

Time:05-27

I have the following code:

NumDf = {'Num1' : [5,7,5,5,5,5,8,5,5,5,5,5,9,5,5,5,5,6,5,5,6], 'Num2' : [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]}
NumDf = pd.DataFrame(NumDf)
NumDf

NumDf['Num1'] <= int(input('Input your number')) <= NumDf['Num2']
# the above code gives me an error

My goal is to produce another column in NumDf that has True/False values for the above equation. I would then filter NumDf for all True values.

Note: The above equation gives me errors. I'm looking for a True if the entered number by the user is between Num1 and Num2 for all rows of the data frame. Example: If a user enters number 6, it would be True for the first row of the data frame, but it would be False for the second row.

CodePudding user response:

You can read your test value into a variable, and then create a new column as the and of the two conditions:

test = int(input('Input your number'))
NumDf['test'] = (NumDf['Num1'] <= test) & (NumDf['Num2'] >= test)

For example, if the input was 6 the result would be:

    Num1  Num2   test
0      5    10   True
1      7    10  False
2      5    10   True
3      5    10   True
4      5    10   True
5      5    10   True
6      8    10  False
7      5    10   True
8      5    10   True
9      5    10   True
10     5    10   True
11     5    10   True
12     9    10  False
13     5    10   True
14     5    10   True
15     5    10   True
16     5    10   True
17     6    10   True
18     5    10   True
19     5    10   True
20     6    10   True

CodePudding user response:

NumDf = {'Num1' : [5,7,5,5,5,5], 'Num2' : [10,10,10,10,10,10]}
NumDf = pd.DataFrame(NumDf)

numbers = []
while len(numbers) < 6:
  numbers.append(int(input('Input your number: ')))

NumDf['Input'] = numbers
NumDf['Check'] = NumDf.apply(lambda x: (x.Num1 <= x.Input) & (x.Input <= x.Num2), axis = 1)
NumDf
index Num1 Num2 Input Check
0 5 10 6 true
1 7 10 11 false
2 5 10 7 true
3 5 10 22 false
4 5 10 8 true
5 5 10 33 false
  • Related