根据条件修改列值

时间:2021-06-05 15:08:48

标签: python string dataframe

我有这个数据框:

Pollster    Banned   Grade
0   Monmouth University     no  A+
1   Selzer & Co.    no  A+
2   ABC News/The Washington Post    no  A+
3   Siena College/The New York Times Upshot     no  A+
4   Field Research Corp. (Field Poll)   no  A/B

我想更改 Grade 列的值,以便

  • A+ --> A
  • A- --> A
  • A/B --> B

我已设法使用以下命令将 A/B 更改为 B

pollster_ratings['Grade_1'] = pollster_ratings['538 Grade'].str.split("/",1).str[1]
pollster_ratings.head()

Pollster    Banned   Grade  Grade_1
0   Monmouth University     no  A+  NaN
1   Selzer & Co.    no  A+  NaN
2   ABC News/The Washington Post    no  A+  NaN
3   Siena College/The New York Times Upshot     no  A+  NaN
4   Field Research Corp. (Field Poll)   no  A/B     B

但我不知道如何仅通过一个命令修改其他值。

谁能帮我解决这个问题(:?

1 个答案:

答案 0 :(得分:1)

使用正则表达式:

pollster_ratings['Grade_1'] = pollster_ratings['Grade'].str.replace('[+\-]$|^A/', '', regex=True)

或者,您也可以将带有替换值的字典传递给 replace