Home > Net >  Numbers Between 2 Columns of Integers
Numbers Between 2 Columns of Integers

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 get the error

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

because in python, a <= b <= c is syntactic sugar for (a <= b) and (b <= c).

Applying that to your case, you are effectively doing

(NumDf['Num1'] <= something) and (something <= NumDf['Num2'])

Now, NumDf['Num1'] <= something gives you a series of booleans, as does (something <= NumDf['Num2']). The implementation of the logical and operator for a pandas.Series doesn't know what to do with (a and b) when either of those two are themselves pandas.Series objects, and so it throws that error.

The solution is to use the bitwise and operator, which performs the operation element-wise on the two Series. Of course, since you're going to have to execute two separate comparisons, you're going to have to ask for the input before you do these comparisons.

>>> num = int(input("Enter a number: "))
>>> (NumDf['Num1'] <= num) & (num <= NumDf['Num2'])

0      True
1     False
2      True
...
18     True
19     True
20     True
dtype: bool

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
  • Related