![](/img/trans.png)
[英]find difference between any two columns of dataframes with a common key column pandas
[英]python / pandas - Find common columns between two dataframes, and create another one with same columns showing their difference
我的 pandas 版本是:
pd.__version__
'0.25.3'
我有两个dataframes
,下面是一个示例,两个数据dataframes
的大部分列都相同。 我试图找到公共columns
,并创建一个新的dataframe
,其中包含显示它们值差异的所有公共columns
。
来自c_r
dataframe 的示例:
Comp_name EOL - CL Per $ Access - CL Per $ Total Impact - CL Per $
Nike -0.02 -0.39 -0.01
Nike -0.02 -0.39 -0.02
Adidas -0.02 -0.39 -0.01
Adidas -0.02 -0.39 -0.02
来自x
dataframe 的示例:
Comp_name EOL - CL Per $ Access - CL Per $ Total Impact - CL Per $
Nike -0.02 -0.39 0.05
Nike -0.02 -0.39 0.03
Adidas -0.02 -0.39 0.08
Adidas -0.02 -0.39 0.08
new_df:
具有相同的列名,并显示差异,即:)
EOL - CL Per $ - Diff Access - CL Per $ - Diff Total Impact - CL Per $ - Diff
-0.00 -0.00 -0.06
-0.00 -0.00 -0.05
-0.00 -0.00 -0.09
-0.00 -0.00 -0.10
我试过了 -请查看代码中的错误位置:
new_df = pd.DataFrame()
for i in c_r:
for j in x:
if c_r[i].dtype != object and x[j].dtype != object:
if i == j:
## THE ISSUE IS IN THE LINE BELOW ##
new_df[i+'-Diff'] = (c_r[i]) - (x[j])
else:
pass
但出于某种原因,我只得到 1 行值。
关于为什么我的代码不起作用的任何想法? 我怎样才能得到结果 dataframe,包括Comp_name
的初始列?
谢谢大家。
您是否尝试过使用 intersection/ symmetric_difference(for difference) 即
a = dataframe2.columns.intersection(dataframe1.columns)
print(a)
I think I understood the problem now, I have a small code as below.
import pandas as pd
d = {'col1': [-0.02 , -0.02 ,-0.02 ,-0.02 ], 'col2': [-0.39, -0.39, -0.39, -0.39],'col3': [-0.01,-0.02,-0.01,-0.02]}
d1 = {'col1': [-0.02 , -0.02 ,-0.02 ,-0.02 ], 'col2': [-0.39, -0.39, -0.39, -0.39],'col3': [0.05,0.03,0.06,0.04]}
df = pd.DataFrame(data=d)
df2 = pd.DataFrame(data=d1)
df = df.apply(pd.to_numeric, errors='coerce')
df2 = df2.apply(pd.to_numeric, errors='coerce')
print(df)
print(df2)
col1 = df.col1 - df2.col1
col2 = df.col2 - df2.col2
col3 = df.col3 - df2.col3
dfnew = pd.concat([col1, col2,col3], axis=1)
print(type(col1))
print(dfnew)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.