Conditional for loop in python

while loop in python
python for loop with if filter
python if statement multiple conditions
python for if one line
pythonic for loop
elif python
python shorthand for loop with if
if statement for list in python

I have two DataFrames: dfSide0 and dfSide1 that have the same columns but a different number of rows. dfSide0 has 17096 rows and dfSide1 has 4961 rows. What I want to do is get the minimum of all possible subtractions between the values of dfSide0['distoperator'] and dfSide1['distoperator'] but only when the condition dfSide0['camera_row'] == dfSide1['camera_row'] is True.

So I do the following:

temp = []
for i in dfSide0['distoperator']:
    if dfSide0['camera_row'] == dfSide1['camera_row']:
        c = min(abs(i - dfSide1['distoperator']))
        temp.append(c)

and I get the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-225-625fcefe40b7> in <module>()
      1 temp = []
      2 for i in dfSide0['distoperator']:
----> 3     if dfSide0['camera_row'] == dfSide1['camera_row']:
      4         c = min(abs(i - dfSide1['distoperator']))
      5         temp.append(c)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops.py in wrapper(self, other, axis)
   1188 
   1189         elif isinstance(other, ABCSeries) and not self._indexed_same(other):
-> 1190             raise ValueError("Can only compare identically-labeled "
   1191                              "Series objects")
   1192 

ValueError: Can only compare identically-labeled Series objects

What should I do?

Thank you for your quick respone. To make things more clear: dfSide0 and dfSide1 both have two columns: 'distance' which is a float and 'camera_row' which is a string with the values 'a', 'b', 'c', 'd', 'e' and 'f' dfSide0 has 17096 rows and dfSide1 has 4961 rows. I need to subtract all the values in column 'distance' between the two dataframes and find the minimum, but only when the value in column 'camera_row' is the same. The exact code so far is the following:

temp = []
for i in dfSide0['distance']:
    c = min(abs(i - dfSide1['distance']))
    temp.append(c)

and it works, but I haven't found a way to accually do this for loop only when

dfSide0['camera_row'] == dfSide1['camera_row']

Using else conditional statement with for loop in python , But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement. Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable. Conditional loops are way to repeat something while a certain condition is satisfied, or True. If the condition is always satisfied (never becomes False), the loop can become infinite. If the condition starts off false, the code in the loop will never run! In Python conditional loops are defined with the while statement:

if I do this:

temp = []
for i in dfSide0['distoperator']:
    if dfSide0['camera_row'] == dfSide1['camera_row']:
        c = min(abs(i - dfSide1['distoperator']))
        temp.append(c)

I get the following:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-222-625fcefe40b7> in <module>()
      1 temp = []
      2 for i in dfSide0['distoperator']:
----> 3     if dfSide0['camera_row'] == dfSide1['camera_row']:
      4         c = min(abs(i - dfSide1['distoperator']))
      5         temp.append(c)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\ops.py in wrapper(self, other, axis)
   1188 
   1189         elif isinstance(other, ABCSeries) and not self._indexed_same(other):
-> 1190             raise ValueError("Can only compare identically-labeled "
   1191                              "Series objects")
   1192 

ValueError: Can only compare identically-labeled Series objects

without the if statement it runs fine.

Conditional Loops, loop can become infinite. If the condition starts off false, the code in the loop will never run! In Python conditional loops are defined with the while statement:. Also, using a for-loop instead of a while-loop will make all of this a little easier. – Raymond Hettinger May 19 '13 at 4:01 @Makoto, that's wrong in three aspects: list is a built-in type and not a function; you don't override it but simply shadow the name in the scope of the variable; and it doesn't directly cause problems unless you also

I think I found the answer:

temp = []
k = -1
for i in dfSide0['distoperator']:
    k = k+1
    j = dfSide0.index[k]
    c = min(abs(i - dfSide1['distoperator'][dfSide1['camera_row'] == dfSide0['camera_row'][j]]))
    temp.append(c)

It seems to work!

4. More Control Flow Tools, The for statement in Python differs a bit from what you may be used to in C or pass can be used is as a place-holder for a function or conditional body when  The for loop ¶ The for loop processes each item in a sequence, so it is used with Python’s sequence data types - strings, lists, and tuples. Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed. The general form of a for loop is:

Python For Loops and If Statements Combined (Data Science Tutorial), How do you write an IF condition in a for loop? for loops and if statements combined. They are not necessarily considered to be Python basics; this is more like a transition to the intermediate level. Using them requires a solid understanding of Python3’s logic – and a lot of practicing, too.

Conditional loop, should evaluate to a boolean or Boolean otherwise the code will not compile. The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops. Example:

Can you use a for loop inside the condition of an if-else statement , if you want to filter out all the empty sub list from your original sub lists, you will have to do something like below. this will give you all the non  Python For Loops A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

Comments
  • Do you have a MCVE? Otherwise the downvotes will just roll in...
  • Your indentation in your example code is off and for a comparison you use == instead of =. Besides that, it is difficult to help without knowing what your data looks like.
  • If you have a different number of rows, then how can dfSide0['columnx'] == dfSide1['columnx']? You don't compare row-by-row here, but the entire series...
  • Yes, the dataframes have a different number of rows. So how do you suggest that I implement this condition ?
  • == you need to use == and not = for comparisons. Just add if dfSide0['camera_row'] == dfSide1['camera_row']: on the line before the for loop and indent appropriately.