gpt4 book ai didi

python - Pandas 用字典更新数据框

转载 作者:行者123 更新时间:2023-12-03 14:39:44 24 4
gpt4 key购买 nike

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

令人沮丧的方法:

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

最佳答案

您需要 combine_first :

d2.combine_first(d1)

#b
#1 3.0
#2 3.0
#5 6.0

关于python - Pandas 用字典更新数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44339351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com