1

df1

Name English Maths City
Hdhdn  65    50   Xyz
Hdhdhd 70.6    45   Abc
John   67.4    46   Ydh

I want to replace all numeric values for John to 0

Result would look like this

Name English Maths City
Hdhdn  65    50   Xyz
Hdhdhd 70.6    45   Abc
John    0    0   Ydh

I would like to know what would be the fastest way to do it.

MDJ
  • 134
  • 8

2 Answers2

2

Use DataFrame.loc with DataFrame.select_dtypes:

df.loc[df['Name'].eq('John'), df.select_dtypes(np.number).columns] = 0
print (df)
     Name  English  Maths City
0   Hdhdn     65.0     50  Xyz
1  Hdhdhd     70.6     45  Abc
2    John      0.0      0  Ydh
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

If you potentially have mixed dtypes, a robust (but non-vectorized) method could be to use applymap on the "John" rows, then to update the DataFrame in place:

df.update(df.loc[df['Name'].eq('John')]
            .applymap(lambda x: 0 if isinstance(x, (float, int)) else x)
          )

print(df)

NB. assuming the original numbers are int/float, you could add more types to check in isinstance if needed.

Output:

     Name  English  Maths City
0   Hdhdn     65.0     50  Xyz
1  Hdhdhd     70.6     45  Abc
2    John      0.0      0  Ydh
mozway
  • 194,879
  • 13
  • 39
  • 75