简体   繁体   English

如何比较具有相同列但行数不同的两个数据帧?

[英]How to compare two data frames with same columns but different number of rows?

df1= DF1 =

  A   B  C  D

  a1  b1 c1 1

  a2  b2 c2 2

  a3  b3 c3 4

df2= DF2 =

  A   B  C  D

  a1  b1 c1 2

  a2  b2 c2 1

I want to compare the value of the column 'D' in both dataframes. 我想比较两个数据帧中列“ D”的值。 If both dataframes had same number of rows I would just do this. 如果两个数据框的行数相同,我将这样做。

newDF = df1['D']-df2['D'] newDF = df1 ['D']-df2 ['D']

However there are times when the number of rows are different. 但是,有时行数不同。 I want a result Dataframe which shows a dataframe like this. 我想要一个显示这样的数据框的结果数据框。

resultDF= resultDF =

  A   B  C  D_df1 D_df2  Diff

  a1  b1 c1  1     2       -1

  a2  b2 c2  2     1        1

EDIT: if 1st row in A,B,C from df1 and df2 is same then and only then compare 1st row of column D for each dataframe. 编辑:如果df1和df2在A,B,C中的第一行相同,则仅对每个数据帧比较D列的第一行。 Similarly, repeat for all the row. 同样,对所有行重复此操作。

Use merge and df.eval 使用mergedf.eval

df1.merge(df2, on=['A','B','C'], suffixes=['_df1','_df2']).eval('Diff=D_df1 - D_df2')

Out[314]:
    A   B   C  D_df1  D_df2  Diff
0  a1  b1  c1      1      2    -1
1  a2  b2  c2      2      1     1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 并排比较相同列但不同行的两个数据框 - Compare two data frames side by side for same columns but different rows 如何比较两个不同数据框中的两列并计算出现次数 - how to compare two columns in two different data frames and count the occurrences Python Pandas - Concat两个具有不同行数和列数的数据帧 - Python Pandas - Concat two data frames with different number of rows and columns 我如何基于相同的ID比较两个不同数据框中的日期列 - how do i compare date columns in two different data frames based on the same ID 如何比较python中两个不同数据框的列? - how to compare columns of two different data frames in python? 如何比较两个不同数据帧的列并保持公共值 - How to compare columns of two different data frames and keep the common values 比较不同数据框中的两个相似列,并为两个数据框取未合并的行 - Compare two similar columns in different data frames and take unmerged rows for both data frame 比较两个不同的熊猫数据框中的两列值 - compare two columns values in two different pandas data frames 连接具有相同分区数但不同列数的两个数据帧(dask) - Concatenate two data-frames (dask) with the same number of partitions but different number of columns 比较 2 个不同数据框的列 - Compare columns of 2 different Data frames
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM