请考虑:

df1 = pd.DataFrame({'a':(1,2,3,4),'b':(10,20,30,40),'c':(100,200,300,400)})
df2 = pd.DataFrame({'a':(1,2,3),'b':(10,20,30),'c':(1111,2222,3333)})
df1:            df2:
    a   b   c           a   b   c
0   1   10  100     0   1   10  1111
1   2   20  200     1   2   20  2222
2   3   30  300     2   3   30  3333
3   4   40  400

执行以下操作:

df1.set_index(['a', 'b']).loc[df2.set_index(['a', 'b']).index, 'c'] = df2.c

我对df1的期望是:

    a   b   c
0   1   10  1111
1   2   20  2222
2   3   30  3333
3   4   40  400

结果是:

    a   b   c
0   1   10  100
1   2   20  200
2   3   30  300
3   4   40  400

你能帮我实现我的预期目标并解释我的失败吗?

推荐答案

df1.set_index(['a', 'b']).loc[df2.set_index(['a', 'b']).index, 'c']创建一个新的DataFrame,您可以为其赋值,然后将其删除,因为它没有分配给变量名.

如果你有一个范围指数,你可以mergecombine_first:

out = df1[['a', 'b']].merge(df2, on=['a', 'b'], how='left').combine_first(df1)

对于任意索引并就地赋值:

df1['d'] = (df1[['a', 'b']].reset_index()
            .merge(df2, on=['a', 'b'], how='left')
            .set_index('index')['c']
            .fillna(df1['c'])
           )

NB. this is assuming that there is no duplicated combination of 100/101 in 102.

输出:

   a   b       c
0  1  10  1111.0
1  2  20  2222.0
2  3  30  3333.0
3  4  40   400.0

Python相关问答推荐

try 使用tensorFlow.keras.models时optree Import错误

Pandas使用过滤器映射多列

当pip为学校作业(job)安装sourcefender时,我没有收到匹配的分发错误.我已经try 过Python 3.8.10和3.10.11

保留包含pandas pandras中文本的列

使用Python进行网页抓取,没有页面

按 struct 值对Polars列表[struct[]]排序

pyautogui.locateOnScreen在Linux上的工作方式有所不同

使用LineConnection动画1D数据

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

Pandas 都是(),但有一个门槛

我们可以为Flask模型中的id字段主键设置默认uuid吗

driver. find_element无法通过class_name找到元素'""

如何在表中添加重复的列?

当点击tkinter菜单而不是菜单选项时,如何执行命令?

python中的解释会在后台调用函数吗?

计算天数

lityter不让我输入左边的方括号,'

matplotlib图中的复杂箭头形状

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

ConversationalRetrivalChain引发键错误