更新pandas数据帧中的值

时间:2016-11-09 09:17:54

标签: python pandas dictionary dataframe replace

我想更新数据框中的字段:

df = pd.DataFrame([
    {'Name': 'Paul', 'Book': 'Plane', 'Cost': 22.50},
    {'Name': 'Jean', 'Book': 'Harry Potter', 'Cost': 2.50},
    {'Name': 'Jim', 'Book': 'Sponge bob', 'Cost': 5.00}
])

          Book  Cost  Name
0         Plane  22.5  Paul
1  Harry Potter   2.5  Jean
2    Sponge bob   5.0   Jim

使用此字符串更改名称:

{"Paul": "Paula", "Jim": "Jimmy"}

得到这个结果:

          Book  Cost  Name
0         Plane  22.5  Paula
1  Harry Potter   2.5  Jean
2    Sponge bob   5.0   Jimmy

任何想法?

1 个答案:

答案 0 :(得分:1)

我认为您dictionary d需要replace

d = {"Paul": "Paula", "Jim": "Jimmy"}
df.Name = df.Name.replace(d)
print (df)
           Book  Cost   Name
0         Plane  22.5  Paula
1  Harry Potter   2.5   Jean
2    Sponge bob   5.0  Jimmy

另一个解决方案mapcombine_first - map返回NaN不匹配,因此需要将其替换为原始值:

df.Name = df.Name.map(d).combine_first(df.Name)
print (df)
           Book  Cost   Name
0         Plane  22.5  Paula
1  Harry Potter   2.5   Jean
2    Sponge bob   5.0  Jimmy