Python 如何动态更新数据帧中的值
谢谢你看我的问题!我试图使用数据帧中已经存在的值动态更新数据帧中的一些值 我知道我可以使用Python 如何动态更新数据帧中的值,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,谢谢你看我的问题!我试图使用数据帧中已经存在的值动态更新数据帧中的一些值 我知道我可以使用loc方法进行查找,并将找到的值更新为静态值。例如: 将熊猫作为pd导入 customers=pd.DataFrame({'id':[1,2,3], 'name':['foo','bar','foo'], “余额”:[100200,-300]}) customers.loc[(customers['name']='foo')&(customers['id']==3),['balance']=300 打印(客
loc
方法进行查找,并将找到的值更新为静态值。例如:
将熊猫作为pd导入
customers=pd.DataFrame({'id':[1,2,3],
'name':['foo','bar','foo'],
“余额”:[100200,-300]})
customers.loc[(customers['name']='foo')&(customers['id']==3),['balance']=300
打印(客户)
#{'id':[1,2,3],'name':['foo','bar','foo'],'balance':[100200300]}
但我尝试使用数据帧中已经存在的值动态更新该值,例如:
customers=pd.DataFrame({'id':[1,2,3],
'name':['foo','bar','foo'],
“余额”:[100200,-300]})
customers.loc[(customers['name']='foo')和(customers['id']==1),['balance']=\abs('balance'))
我希望这会将loc
查询中的所有值更新为正整数。当然,这是一个只有一个匹配项的简单示例:)
有没有一种方法可以动态访问/更新像这样的数据帧中的值?谢谢大家!
pandas
是索引
敏感的,因此当您指定值时,隐藏键是索引
,它将与索引
匹配,以便您只需应用一次条件
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
非常感谢你!您是否知道文档中包含了哪些内容,以便我可以阅读更多内容?我和熊猫医生相处得很艰难。