简体   繁体   English

组合两个数据框并显示它们的差异-Python Pandas

[英]Combining two data frames and showing their difference - Python Pandas

I have two dataframes which will be pulled from CSV files: 我有两个将从CSV文件中提取的数据框:

   X     Value 1  Value 2
0  1     2        1      
1  3     4       -2      
2  3     3        8      
3 -1     4        2      
4  6    -8        2      
5  0     10       1

   X     Value 1  Value 2
0  1     2        1      
1  3     4       -1      
2  3     4        8      
3 -1     4        2      
4  6    -8        2      
5  0     9        1 

I would like to use Python Pandas to have an output like this, where it would be the second data frame but for any values that have changed there will be a plus/minus in brackets of the amount it has changed by: 我想使用Python Pandas获得这样的输出,它将是第二个数据帧,但是对于任何已更改的值,括号中的值将通过以下方式加/减:

   X     Value 1  Value 2
0  1     2        1      
1  3     4       -1 (+1)     
2  3     4 (+1)   8      
3 -1     4        2      
4  6    -8        2      
5  0     9 (-1)  1 

The only thing close to a solution I found online made use of Panels with are deprecated so I want to avoid using them. 我发现在网上发现与Panels一起使用的解决方案的唯一方法已被弃用,因此我想避免使用它们。 Also I would like the final output to be a dataframe so that I can apply styles to it. 另外,我希望最终输出是一个数据框,以便可以对其应用样式。

You can use sub with applymap first and last add original df2 converted to string s: 您可以applymap subapplymap一起使用,最后add转换为string s的原始df2

  • if length of both DataFrames is same 如果两个DataFrame的长度相同
  • if values of indexes are same in both DataFrames 如果两个DataFrames的索引值相同
  • if columns names are same in both DataFrames 如果两个DataFrames列名称相同

df = df2.sub(df1).applymap(lambda x: ' ({0:+d})'.format(x) if x != 0 else '')
print (df)
  X Value 1 Value 2
0                  
1              (+1)
2      (+1)        
3                  
4                  
5      (-1) 

df3 = df2.astype(str).add(df)
print (df3)
   X Value 1  Value 2
0  1       2        1
1  3       4  -1 (+1)
2  3  4 (+1)        8
3 -1       4        2
4  6      -8        2
5  0  9 (-1)        1

You can get the difference between df2 and df1 and create the + or - flag and then append this to df2. 您可以得到df2和df1之间的差异,并创建+或-标志,然后将此附加到df2。

df2.astype(str) + \
(df2-df1).applymap(lambda x: ' ({}{})'\
                   .format('+' if x > 0 else '', str(x)).replace('(0)',''))

Out[240]: 
     X Value 1  Value 2
0   1       2        1 
1   3       4   -1 (+1)
2   3   4 (+1)       8 
3  -1       4        2 
4   6      -8        2 
5   0   9 (-1)       1     

Without formatting skills : 没有格式化技巧:

(df2.astype(str)+"("+(df2-df1).astype(str)+")").applymap(
lambda s:s.replace("(0)","").replace("(","(+").replace("+-","-"))

for : 为:

    X Value1  Value2
0   1      2       1
1   3      4  -1(+1)
2   3  4(+1)       8
3  -1      4       2
4   6     -8       2
5   0  9(-1)       1

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM