如何将pandas数据框中的字符串条目转换为整数?

我正在使用的pandas数据框有一个包含字符串条目的列,我希望将其转换为整数。

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

但这不会改变任何东西吗?

评论
ueaque
ueaque

You can use map to do this

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