我正在尝试使用 DataFrame 中已存在的值动态更新 Pandas DataFrame 中的某些值。我知道我可以使用该loc方法进行查找并将找到的值更新为静态值。例如:import pandas as pdcustomers = pd.DataFrame({'id': [1, 2, 3], 'name': ['foo', 'bar', 'foo'], 'balance': [100, 200, -300]})customers.loc[(customers['name']=='foo') & (customers['id']==3), ['balance']] = 300print(customers)# {'id': [1, 2, 3], 'name': ['foo', 'bar', 'foo'], 'balance': [100, 200, 300]}但我正在尝试使用 DataFrame 中已经存在的值动态更新值,例如:customers = pd.DataFrame({'id': [1, 2, 3], 'name': ['foo', 'bar', 'foo'], 'balance': [100, 200, -300]})customers.loc[(customers['name']=='foo') & (customers['id']==1), ['balance']] = #abs('balance')我希望这会将loc查询中的所有值更新为正整数。当然,这是一个只有一个匹配的简单示例 :)有没有办法像这样动态访问/更新 Pandas DataFrame 中的值?谢谢!
1 回答
杨魅力
TA贡献1811条经验 获得超6个赞
pandas是index敏感的,因此当您分配隐藏键的值时index,它将匹配index,因此您只需应用条件一次。
customers.loc[(customers['name']=='foo') & (customers['id']==1), ['balance']] =customers.balance.abs()
customers
Out[112]:
balance id name
0 100 1 foo
1 200 2 bar
2 300 3 foo
添加回答
举报
0/150
提交
取消
