Python / Pandas-更新一组记录的数据

我正在尝试更新一些数据,但是我需要更新的数据是我用来选择唯一记录的列的一部分.

import pandas as pd

data = [{'subid':'123','grade':'K'},{'subid':'123','grade':'3rd'}, {'subid':'123','grade':'6th'}, {'subid':'456','grade':'1st'},{'subid':'456','grade':'3rd'},{'subid':'456','grade':'5th'}]
df = pd.DataFrame(data)
df

我正在尝试使用str.replace

df['grade'][df['subid']== '456'].str.replace('3rd','4th')

我得到以下信息,但无法更新df.

3  1st
4  4th
5  5th
Name: grade, dtype: object

df
  grade     subid
0   K       123
1   3rd     123
2   6th     123
3   1st     456
4   3rd     456
5   5th     456

尝试获取以下内容作为最终的df

  grade     subid
 0  K       123
 1  3rd     123
 2  6th     123
 3  1st     456
 4  4th     456
 5  5th     456

有更好的更新方法吗?

最佳答案

尝试这个:

In [138]: df.loc[df['subid']== '456', 'grade'] = df.grade.replace({'3rd':'4th'})

In [139]: df
Out[139]:
  grade subid
0     K   123
1   3rd   123
2   6th   123
3   1st   456
4   4th   456
5   5th   456