Python 当您知道列和行引用时,如何更改数据框中的字段值
我有一个名为Python 当您知道列和行引用时,如何更改数据框中的字段值,python,pandas,dataframe,indexing,Python,Pandas,Dataframe,Indexing,我有一个名为df的大数据帧,看起来像: First Name Last name Dept Location Status Concat 0 Jo Jones Accounts Bristol Current JonesJo 1 Sid Smith Sales Hull New SmithSid 2 Phi
df
的大数据帧,看起来像:
First Name Last name Dept Location Status Concat
0 Jo Jones Accounts Bristol Current JonesJo
1 Sid Smith Sales Hull New SmithSid
2 Phil Evans Production Hull Current EvansPhil
3 Sarah Heath Marketing Bristol Current HeathSarah
4 Jane Hill Accounts Bristol Current HillJane
5 Amy Cooper Sales Hull Current CooperAmy
23453 Marcus Price Operations Hull Current PriceMarcus
23454 Andrew King Design Bristol Current KingAndrew
23455 Emma Lane Marketing Bristol Current LaneEmma
23456 Brian Deen Accounts Bristol Current DeenBrian
23457 Steve Jacks Design Bristol Current JacksSteve
如果您知道要更改的字段的“坐标”,是否有方法更改记录中的字段值
例如,我试图将Amy Cooper的“部门”值从“销售”改为“账户”,我可以这样做吗:
value = 'Accounts'
ConcatName = 'CooperAmy'
columnName = 'Dept'
df.ix[df['Concat']= ConcatName ,columnName ] = value
注意。所有Concat值都是唯一的
因此,我的结果数据框如下所示:
First Name Last name Dept Location Status Concat
0 Jo Jones Accounts Bristol Current JonesJo
1 Sid Smith Sales Hull New SmithSid
2 Phil Evans Production Hull Current EvansPhil
3 Sarah Heath Marketing Bristol Current HeathSarah
4 Jane Hill Accounts Bristol Current HillJane
5 Amy Cooper Accounts Hull Current CooperAmy
23453 Marcus Price Operations Hull Current PriceMarcus
23454 Andrew King Design Bristol Current KingAndrew
23455 Emma Lane Marketing Bristol Current LaneEmma
23456 Brian Deen Accounts Bristol Current DeenBrian
23457 Steve Jacks Design Bristol Current JacksSteve
假设
'First Name'
和'Last Name'
的组合在数据帧中是唯一的,则可以使用多索引
,然后通过以下方式设置标量:
更改索引后,您不能再通过df['First Name']
访问您的系列。为此,请使用df.index.get_level_值('First Name')
。如果在后续阶段再次需要索引作为列,可以使用df=df.reset\u index()
是一个更复杂的索引工具,当您有多个值要设置/替换时更可取。这将起作用,除非您需要
=
:df.ix[df['Concat']==ConcatName,columnName]=value
,而且您应该loc
因为ix
已弃用df.loc[df['Concat']==ConcatName,columnName]=值
可以使用.at以获得更好的性能
df = df.set_index(['First Name', 'Last name'])
df.at[('Amy', 'Cooper'), 'Dept'] = 'Accounts'