【问题标题】:compare two dataframes and get nearest matching dataframe比较两个数据帧并获得最近的匹配数据帧
【发布时间】:2020-06-29 18:59:20
【问题描述】:

有两个带列的数据框

df1


name    cell     marks  

tom      2       21862


df2


name    cell    marks     passwd

tom      2       11111      2548

matt     2       158416      2483
         2       21862      26846

如何比较 df2 和 df1 并获得最接近的匹配数据帧

预期输出:

df2


name    cell    marks     passwd

tom      2       11111      2548
         2       21862      26846

试过merge,但数据是动态的。在一种情况下name 可能会改变,在另一种情况下marks 可能会改变

【问题讨论】:

标签: python python-3.x pandas dataframe compare


【解决方案1】:

您可以尝试以下方法:

import pandas as pd
dict1 = {'name': ['tom'], 'cell': [2], 'marks': [21862]}
dict2 = {'name': ['tom', 'matt'], 'cell': [2, 2],
         'marks': [21862, 158416], 'passwd': [2548, 2483]}

df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)

compare = df2.isin(df1)
df2 = df2.iloc[df2.where(compare).dropna(how='all').index]
print(df2)

输出:

  name  cell  marks  passwd
0  tom     2  21862    2548

【讨论】:

  • 更新的问题,你的回答在这种情况下不起作用。
【解决方案2】:

您可以将pandas.mergeindicator=True 选项一起使用,过滤'both' 的结果:

import pandas as pd

df1 = pd.DataFrame([['tom', 2, 11111]], columns=["name", "cell", "marks"])

df2 = pd.DataFrame([['tom', 2, 11111, 2548],
                    ['matt', 2, 158416, 2483]
                    ], columns=["name", "cell", "marks", "passwd"])


def compare_dataframes(df1, df2):
    """Find rows which are similar between two DataFrames."""
    comparison_df = df1.merge(df2,
                              indicator=True,
                              how='outer')
    return comparison_df[comparison_df['_merge'] == 'both'].drop(columns=["_merge"])


print(compare_dataframes(df1, df2))

返回:

  name  cell  marks  passwd
0  tom     2  11111    2548

【讨论】:

  • 更新的问题,你的回答在这种情况下不起作用。
猜你喜欢
  • 2019-10-07
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 2017-06-12
  • 2021-09-15
  • 2019-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多