在数据框中迭代行,并根据其他列更改列的值

5
假设我有一个名为df的数据框,它看起来像下面展示的这样:
Id      Place        
1        NY        
2       Berlin          
3       Paris        
4       Paris         
5       Berlin       

还有一个字典,以ID作为键,以位置作为值,如下所示:

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

我想遍历数据框的每一行,查看ID是否包含在id_to_place字典中。如果是这样,则我想将该行的Place列替换为字典值。例如,在运行代码后,我希望输出如下:
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)

但是当我运行这段代码时,数据框仍然保持不变。有没有人知道为什么会发生这种情况?感激任何帮助!
3个回答

5

使用Series.map来替换匹配的值,然后使用Series.fillnaNaN替换为原始列:

df['Place'] = df['Id'].map(id_to_place).fillna(df['Place'])
print (df)
   Id   Place
0   1  Berlin
1   2  Berlin
2   3      NY
3   4   Paris
4   5  Berlin

3

您当前的方法无法正常工作,因为您的字典中的条目是整数,并且您正在将它们与始终返回False的str(id)进行比较。如果您删除str并仅检查item是否与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)

0
你可以从字典中构建一个DataFrame,以向量化的方式分配值:
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接