0

I have a dataframe I want to iterate through using a function, but can't seem to use itertools correctly. The below nested for loop works fine!

columns = len(df_test.columns)
rows = len(df_test.index)
list = []
list2 = []

def inRange(df, min, max):
    for i in range(rows):
        x = 0
        for j in range(columns):
            if df_test.iloc[i, j] >= min and df_test.iloc[i, j] <= max:
                x = x + 1
            else:
                x = x + 0
                list2.append((i, j))
    if x == columns:
        list.insert(i, "True")
        # print("True")
    else:
        # print("False")
        list.insert(i, "False")

When I use itertools, it does not. It gives only 1 False value added into the list, when it should be [False, True, True, False].

def inRange(df, min, max):
    x = 0
    # i = index, j = columns
    for i, j in itertools.product(range(rows), range(columns)):
        if df_test.iloc[i, j] >= min and df_test.iloc[i, j] <= max:
            x = x + 1
        else:
            x = x + 0
            list2.append((i, j))
    if x == columns:
        list.insert(i, "True")
        # print("True")
    else:
        # print("False")
        list.insert(i, "False")

Expected: list = [False, True, True, False]

list2 = [(0, 0), (0, 1), (0, 3), (3, 2), (3, 3)]

list 2 works fine and gives the correct result.

edit02
  • 15
  • 6
  • 1
    You should always include a minimal example of the data/input with your [mre]. [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). – wwii Jan 08 '23 at 23:48
  • I haven't looked deeply, but immediately notice that you reset `x` on every iteration of the `i` loop, and do no such thing in the `itertools` version. – Grismar Jan 09 '23 at 00:06
  • `Expected: list = [False, True, True, False]` - Can you say in words what you are trying to do? Like: `True if any row in a column is between two values` or `True if all rows in a column are between two values` or `True if any column in a row is between two values` or ``True if all columns in a row is between two values`. – wwii Jan 09 '23 at 00:06
  • 2
    Your code has extremely strong "XY Problem" vibes. What problem are you really trying to solve here? What DataFrame would you typically pass to this function, and why do you need a lists of strings reading `'True'` or `'False'` based on its contents? What do you hope to achieve by wedging `itertools` in here? (it's very likely pandas has some simple way to achieve your actual goal) Also, don't name variables `list` shadows the type. – Grismar Jan 09 '23 at 00:09
  • The if/else statement `if x == columns:...` in your first example doesn't look like it is indented correctly. – wwii Jan 09 '23 at 00:13
  • `df.apply(pd.Series.between,args=(min_value,max_value),axis=0).all(1)` - pretty sure that's what you are after. – wwii Jan 09 '23 at 00:20

0 Answers0