繁体   English   中英

如何动态更新Pandas DataFrame中的值

[英]How to dynamically update a value in a Pandas DataFrame

感谢您看我的问题! 我正在尝试使用DataFrame中已经存在的值动态更新Pandas DataFrame中的某些值。

我知道我可以使用loc方法进行查找,并将找到的值更新为静态值。 例如:

import pandas as pd

customers = pd.DataFrame({'id': [1, 2, 3],
                          'name': ['foo', 'bar', 'foo'],
                          'balance': [100, 200, -300]})

customers.loc[(customers['name']=='foo') & (customers['id']==3), ['balance']] = 300

print(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中的值? 谢谢!

pandasindex敏感的,因此当您指定值时,隐藏键为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM