Skip to content Skip to sidebar Skip to footer

Loop For Iterating Through Two Lists Is Not Working

I am trying to use a loop for iterating through two lists. Unfortunately, the second for loop does not work: it only checks the first item within the list, but not with rest. Could

Solution 1:

You should not use loops when you work with Pandas. DataFrames are not designed to be accessed sequentially. You need some NumPy, though:

import numpy as np
df['Cars']   = np.where(df['Engine to check'].isin(low_cars_engines), 'Yes', 'No') 
df['Planes'] = np.where(df['Engine to check'].isin(low_planes_engines), 'Yes', 'No')

Result:

#     Engine to check Cars Planes
# 0               Audi  Yes     No
# 1  CFM International   No     No
# 2        Rolls-Royce   No    Yes
# 3            Bentley  Yes     No
# 4         Volkswagen   No     No
# 5             Toyota   No     No
# 6             Suzuki   No     No
# 7            Porsche  Yes     No

You probably should not use "Yes" and "No," either. Use boolean values True and False instead, as they are easier to work with in the future:

df['Cars']   = df['Engine to check'].isin(low_cars_engines) 
df['Planes'] = df['Engine to check'].isin(low_planes_engines)

Finally, if everything in the DataFrame is strictly a car or a plane, only one column is required. The other will be the complement.


Solution 2:

You have an additional space here

row['Engine to check ']

Try changing it to

row['Engine to check']

Post a Comment for "Loop For Iterating Through Two Lists Is Not Working"