2017-06-03 8 views
0

Ich habe einen Datenrahmen und ein Wörterbuch, das ich so kombinieren möchten, dass das Wörterbuch des Datenrahmens überschreibt, wenn ihre Schlüssel schneidenPandas Update Datenrahmen mit Wörterbuch

Frustrierende Methode:

import pandas as pd 
# setup input df 
d1 = pd.DataFrame([[1, 2], [5, 6]]) 
d1.columns = ['a', 'b'] 
d1 = d1.set_index('a') 

# setup input dict 
a = {1 : 3, 2: 3} 

# Now how do we join? 
# ~~~~~~~~~~~~~~~~~~~ 

# turn dict into dataframe 
d2 = pd.DataFrame() 
d2 = d2.from_dict(a, orient='index') 
d2.columns = d1.columns 

# update indices that are the same 
d2.update(d1) 
# append indices that are different 
d2 = d2.append(d1.loc[d1.index.difference(d2.index) ]) 
d2 

Antwort

Verwandte Themen