I'm trying to code in Python after a hiatus of 4 years and facing difficulties in implementing my ideas. I have 2 large excel sheets consisting of more than 12k x 70 values, both have the same number of columns and column names. I've created a primary key for both the dataframes and now I want to compare values from the primary key of one sheet to primary key of another and when there's a match I want to replace certain values(not all) from the old sheet to the new.
eg df1:

A   B   C   D   E   F
1   2   3   4   5   6
7   8   9   10  11  12
13  14  15  16  17  18

DF2:

A   B   C   D   E   F
19  20  21  22  23  6
25  26  27  28  29  12  
31  32  33  34  35  19

当手术完成后,我需要它看起来像这样 DF1:

A   B   C   D   E   F
1   2   21  22  23  6
7   8   27  28  29  12  
13  14  15  16  17  18

列F是主键

我try 了下面的方法,但输出结果非常奇怪

for i in df2['F']:
    for j in df1['F']:
        if i==j:
            df1['D'] = df2['D'].astype(str)            
            df1['E'] = df2['E'].astype(str)
            df1['C'] = df2['C'].astype(str)

推荐答案

Merge可用于执行以下操作:

new_df = df1.merge(df2, on='F')

请注意,如果两个数据帧具有相同的列名,那么new_df将包含带有‘_x’和‘_y’后缀的新列名.

合并后,您可以决定保留哪些列

要仅复制值(如果它们存在),您可以:

import numpy as np
new_df['A_x'] = np.where(new_df['A_y'].isnull(), new_df['A_x'], new_df['A_y'])

只有当新值不为空时,它才会更新单元格.

解释n.在哪里: Np.where(,,) 基本上,我是在判断刚刚合并的"new Column"中的值是否为空.如果为空,则用列中的当前值"更新"旧列.如果不为空,则用合并列中的新值更新旧列

Python相关问答推荐

如何推迟对没有公钥的视图/表的反射?

Python在通过Inbox调用时给出不同的响应

已安装' owiener ' Python模块,但在导入过程中始终没有名为owiener的模块

如何在不使用字符串的情况下将namedtuple属性传递给方法?

从 struct 类型创建MultiPolygon对象,并使用Polars列出[list[f64]列

PyQt5如何将pyuic 5生成的Python类添加到QStackedWidget中?

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

即使在可见的情况下也不相互作用

根据不同列的值在收件箱中移动数据

运行Python脚本时,用作命令行参数的SON文本

图像 pyramid .难以创建所需的合成图像

如何在Python数据框架中加速序列的符号化

如何使用Python以编程方式判断和检索Angular网站的动态内容?

我如何根据前一个连续数字改变一串数字?

迭代嵌套字典的值

提取相关行的最快方法—pandas

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

numpy.unique如何消除重复列?

在输入行运行时停止代码

Python Pandas—时间序列—时间戳缺失时间精确在00:00