Python 迭代数据帧中的行,并基于其他列更改列的值

Python 迭代数据帧中的行,并基于其他列更改列的值,python,pandas,dataframe,Python,Pandas,Dataframe,假设我有一个名为df的数据帧,它看起来如下所示: Id Place 1 NY 2 Berlin 3 Paris 4 Paris 5 Berlin id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"} 以及一个字典,其中ID作为键,位置作为值,如下所示: Id Pl

假设我有一个名为df的数据帧,它看起来如下所示:

Id      Place        
1        NY        
2       Berlin          
3       Paris        
4       Paris         
5       Berlin       
id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}
以及一个字典,其中ID作为键,位置作为值,如下所示:

Id      Place        
1        NY        
2       Berlin          
3       Paris        
4       Paris         
5       Berlin       
id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}
我想遍历数据帧的每一行,看看ID是否包含在ID\u to\u place字典中。如果是这样,那么我想用dictionary值替换该行的列位置。例如,在运行代码后,我希望输出为:

Id      Place        
1       Berlin       
2       Berlin          
3       NY        
4       Paris         
5       Berlin       
到目前为止,我已经尝试了以下代码:

id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}

for index,row in df.iterrows():
    id = row['id']
    place = row['place']
    for item in id_to_place:
        if item == str(id):
          df.loc[df.id =id,'place'] = id_to_place[item]

print(df)
但是当我运行代码时,数据帧保持不变。有人知道为什么会这样吗?谢谢你的帮助

用于替换匹配值,然后用原始列替换
NaN
s,替换方式为:


您当前的方法不起作用,因为您的字典中的项是整数,并且您正在根据str(id)检查它们,str(id)总是返回False。如果您删除str,只需根据id检查项目,那么它就可以工作

id_to_place = { 1 : "Berlin", 2: "Berlin", 3: "NY"}

for index,row in df.iterrows():
    id = row['id']
    place = row['place']
    for item in id_to_place:
        if item == id: # this line changed
          df.loc[df.id =id,'place'] = id_to_place[item]

print(df)

您可以从dict构建一个数据帧,以矢量化的方式分配值:

df1 = pd.DataFrame(list(id_to_place.values()), index=id_to_place.keys(),
           columns=['Place'])
df.set_index('Id', inplace=True)
df.loc[df1.index] = df1.Place
df.reset_index(inplace=True)