How to replace a cell value using str.contains function using the index of the row

Viewed 30

I have a data-frame.

    name    degree  score
0   aparna  MBA     90
1   pankaj  BCA     40
2   sudhir  M.Tech  80
3   Geeku   MBA     98

I would like to replace the value in the 'Score' column with 'Informatica', if the value in the column 'degree' in that particular row contains 'BA'. I have managed to replace all the values for the df using the following code.

df.loc[df['degree'].str.contains('BA'), 'score'] = 'Informatica'

This code replaces all values. I want to replace just the value in that row using the index value of that row.

I have written the following snippet.

df.loc[df.index[1], 'degree'].str.contains('BA'), 'score' = 'Informatica'

But this gives me an error.

I want the code to give me this:

    name    degree  score
0   aparna  MBA     Informatica
1   pankaj  BCA     40
2   sudhir  M.Tech  80
3   Geeku   MBA     98
1 Answers

Not so easy, need another condition chained by & for compare index values:

df.loc[(df.index == 0) & df['degree'].str.contains('BA'), 'score'] = 'Informatica'
print (df)
     name  degree        score
0  aparna     MBA  Informatica
1  pankaj     BCA           40
2  sudhir  M.Tech           80
3   Geeku     MBA           98
Related