【问题标题】:compare 2 dataframes and traverse 1st dataframe each n evry row so that validate corresponding column values in 2nd df比较 2 个数据帧并遍历每一行的第一个数据帧,以便验证 2nd df 中的相应列值
【发布时间】:2020-12-14 16:05:37
【问题描述】:

比较 2 个数据帧并每行遍历第一个数据帧,以便验证第二个 df 中的相应列值。 在第 2 个 df 列中,值是唯一的。但在第 1 个 df 中,行可能是 10000 行。 示例代码: '''

import pandas as pd
import numpy as np

data1 = {'unique_id': 
     ['Computer','iPhone','Printer','Desktop','Computer','iPhone','iphpne','Printer','Desktop','Computer','iPhone','Printer','Desktop'],
        'category': 
         ['movies','documentary','series','special','movies','documentary','series','special','series','special','movies','series','special'],
         'subcategory':
         ['drama','horror','comedy','reality','drama','documentary','comedy','reality','documentary','comedy','documentary','comedy','drama']
        }

df1 = pd.DataFrame(data1,columns= ['unique_id', 'category','subcategory'])
print(df1)

data2 = {'unique_id': ['Computer','iPhone','Printer','Desktop'],
         'category': ['movies','documentary','series','special'],
         'subcategory':['drama','horror','comedy','reality']
        }

df2 = pd.DataFrame(data2,columns= ['unique_id', 'category','subcategory'])
print(df2)

''' #output:迭代df1中的每一行,比较对应的所有值#如果不匹配追加索引,则在df2中匹配。

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    您可以通过在merge 函数中指定how='outer' 来实现:

    df1.merge(df2, how='outer')
    

    如果你想保留 df 的行顺序:

    # Append new values to df2 based on non-row-matches from df1
    df2.append(df1.loc[(~df1.isin(df2)).all(axis=1)])
    
    # Or the other way around
    df1.append(df2.loc[(~df2.isin(df1)).all(axis=1)])
    

    【讨论】:

    • 以上没有给出结果。如在 df1 中 10000 行有重复项,在 df1 msy 中是 df1 中已经存在的 20 个唯一行。现在我想比较 df1 中的每一行去签入如果 df2 不在 df2 中,它是否可用,然后从 df1 中拾取该行索引,然后再次从 df1 中获取第 2 行,如果可以,则检查 df2 中的所有行附加索引。谁能帮助我。
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多