2016-11-09 61 views
1

我想在我的數據幀更新字段:更新值

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

我想你需要通過replacedictionaryd

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