gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:42 24 4
gpt4 key购买 nike

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

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

关于Python/Pandas - 更新一组记录的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36107351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com