0

for loop in dataframe I tried this can anyone help me with the correct answer

for i in df['name']:
    if df['name'] = 'Amit':
        print('yes Amit')
    else:
        df['name'] = 'not Amit'
name age city
Amit 45 Pune
Ajay 25 Pune
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
Sufi Ali
  • 1
  • 2
  • 1
    The question is wrong. Never ask: "How to apply a loop on a `dataframe`?". Ask: "How *not* to apply a loop on a `dataframe`?" – Aryerez Jan 14 '23 at 17:45
  • 1
    First of all `=` is assignment, while `==` is comparison. Then the main advantage of a DF is not to use loop – buran Jan 14 '23 at 17:45
  • 1
    Do you want to `print` or to change the values of the DataFrame? – mozway Jan 14 '23 at 19:20

2 Answers2

0

I don't know how is your dataframe but this :

for i, row in df.iterrows():
    if row['name'] == 'Amit':
        df.loc[i, 'name'] = 'yes Amit'
    else:
        df.loc[i, 'name'] = 'not Amit'

Might do what you want.

  • Well he can also do this : df.loc[df['name'] == 'Amit', 'name'].apply(lambda x: print('yes Amit') if x == 'Amit' else print('not Amit')) – TheArcturus Jan 14 '23 at 17:57
0

If we assume that your dataframe is:

df_data = {
     'name' : ['Amit','Peter','Carl','Mary','Amit','Hank','Ali'],
     'age': [45,34,23,56,21,23,45]
     }
df = pd.DataFrame(df_data)
print(df)

Output:

    name  age
0   Amit   45
1  Peter   34
2   Carl   23
3   Mary   56
4   Amit   21
5   Hank   23
6    Ali   45

Basically, if you want to run a 'loop', you should do something like this:

for index, row in df.iterrows():
  if df['name'][index] == 'Amit':
    print('yes Amit')
  else:
    print('not Amit')

Output:

yes Amit
not Amit
not Amit
not Amit
yes Amit
not Amit
not Amit

But usually it is better NOT to do the "loop", and there are always more optimized methods!

df['name'].apply(lambda x: 'yes Amit' if x == 'Amit' else 'not Amit')

Output:

0    yes Amit
1    not Amit
2    not Amit
3    not Amit
4    yes Amit
5    not Amit
6    not Amit

And also:

df['Y/N'] = df['name'] == 'Amit'

Output:

    name  age    Y/N
0   Amit   45   True
1  Peter   34  False
2   Carl   23  False
3   Mary   56  False
4   Amit   21   True
5   Hank   23  False
6    Ali   45  False

Also take a look at: How to iterate over rows in a DataFrame in Pandas