![](/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.