【发布时间】:2021-08-31 06:55:50
【问题描述】:
我有一个下面的数据框,我需要检查所有列的值并确保它们没有更新。
我根据键连接了两个数据框,并且必须比较两个 DataFrames 列,如客户名称、电话、电子邮件,并创建一个新的数据框,其中记录更新和替换值。
例如-:
以下数据框 custid z 已更新电子邮件地址,因为 email != email_update 并且 email 不为空,我们需要创建一个新的数据框,其中包含替换值和操作列。
df1(新数据)
custid custname email phone
x tina z.gmail.com 345-345-3456
y mina z1.gmail.com 445-345-3456
z zina 555-345-3456
df2(旧数据)
custid custname email phone
x tina ze.gmail.com 345-345-3456
y mina z1.gmail.com 315-345-3456
z zina z3@gmail.com 555-345-3456
q pina z4@gmail.com 233-456-3456
df3
custid custname email phone Action
y mina z1.gmail.com 445-345-3456 Update
x. tina z@gmail.com 345-345-3456 Update
q pina z4@gmail.com 233-456-3456 Insert
z. Zina 555-345-3456. None
预期输出-:
比较两个 DataFrame 的 Python 代码。
我正在尝试比较两个 DataFrame 以获得插入、更新和删除的差异。
我能够找出插入和删除部分,但无法获取更新行。
def compare_data(df,df1):
df["Key"] = df["Custid"] + df["Custname"]
df1["Key"] = df1["Custid"] + df1["Custname"]
#########Insert Rows################################################
df_result = pd.merge(df1,df,on = 'Key', how = 'inner',suffixes=['', '_update'])
df3 = df1[~df1['Key'].isin(df_result['Key'])]
#########Delete Rows################################################
df4 = df[~df['Key'].isin(df_result['Key'])]
###############################################################
我尝试过的事情
df5 = pd.concat([df,df1]).drop_duplicates(subset = ['Privilege'],keep= False)
但它不工作并且行停留在那里。
【问题讨论】:
-
你能给我们你的python代码吗?很难确切地说出您要做什么。
-
对于单个
custid_key,custname_updated包含一个值,即使email, phone没有更改。那么条件列是否只有电子邮件?..请发布创建DataFrame的代码。 -
更新后的数据框中的邮件不应该是“z3...”吗?