Ahijit
Ahijit

Reputation: 134

How to convert string entries in pandas dataframe to integers?

The pandas data frame that I was working with has a column with string entries and I wish to convert it to integers.

The column is called diagnosis and each row has a value of either M or B. I wanted to convert all M to 1 and all B to 0 with the following code

for row in data['diagnosis']:
  if row == 'M':
    row = 1
  else:
    row = 0

But it does not change anything?

Upvotes: 0

Views: 157

Answers (1)

fmarm
fmarm

Reputation: 4284

You can use map to do this

data['diagnosis'] = data['diagnosis'].map({'M':1,'B':0})

Upvotes: 2

Related Questions