Home > Blockchain >  I struggle a lot to apply loop in dataframe, How can I improve this?
I struggle a lot to apply loop in dataframe, How can I improve this?

Time:01-15

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

CodePudding user response:

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.

CodePudding user response:

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

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

  • Related