Pandas 用字典更新数据框

Alt*_*ter 7 python pandas

我有一个数据框和一个我想合并的字典,以便字典在它们的键相交时覆盖数据框

令人沮丧的方法:

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
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 3

你需要combine_first

d2.combine_first(d1)

#b
#1  3.0
#2  3.0
#5  6.0
Run Code Online (Sandbox Code Playgroud)