如何在python中比较两个excel列?

如何在python中比较两个excel列?,python,pandas,Python,Pandas,我有两个 Excel 1: A、 B,C 1,2,3 Excel 2: A、 C、B 1,3,2 如何根据excel 1列重新定位excel 2 所以A,C,B变成了A,B,C 我使用以下代码检查列顺序: comparison_Columns = pd.read_excel(xls).columns == pd.read_excel(xls2).columns if all(comparison_Columns): pass else: print('Wrong column o

我有两个

Excel 1:

A、 B,C

1,2,3

Excel 2:

A、 C、B

1,3,2

如何根据excel 1列重新定位excel 2

所以A,C,B变成了A,B,C

我使用以下代码检查列顺序:

comparison_Columns = pd.read_excel(xls).columns == pd.read_excel(xls2).columns
if all(comparison_Columns):
    pass
else:
    print('Wrong column order !!!!! ')

数据是否来自excel或其他格式并不重要。如果您知道这两个列的顺序相同,您可以

作为pd进口熊猫 df0=pd.DataFrame[[1,2,3]],columns=[A,B,C] df1=pd.DataFrame[[1,3,2]],columns=[A,C,B] printdf1[df0.columns] A、B、C 0 1 2 3
此代码段可以正常工作:

def areColumnSame(df1, df2, checkTypes = True):
    if checkTypes:
        type1 = dict(df1.dtypes)
        type2 = dict(df2.dtypes)
        return type1 == type2

    else:
        col1 = list(df1.columns)
        col2 = list(df2.columns)
        col1.sort()
        col2.sort()
        return col1 == col2
为了展示上述代码是如何工作的,让我们来探索以下示例:

考虑三个excel文件:

| A | B | C |
|---|---|---|
| 1 | 2 | 3 |
| 4 | 5 | 6 |

| A | C | B |
|---|---|---|
| 1 | 3 | 2 |
| 4 | 6 | 5 |

| A | B | C | A.1 | B.1 | C.1 |
|---|---|---|-----|-----|-----|
| 1 | 2 | 3 | 1   | 2   | 3   |
| 4 | 5 | 6 | 4   | 5   | 6   |
现在,对于第一个文件,dictdf.dtypes如下所示:

{'A': dtype('int64'),
 'B': dtype('int64'),
 'C': dtype('int64')}
与其他两个文件类似:

{'A': dtype('int64'),
 'C': dtype('int64'),
 'B': dtype('int64')}

我们只需要比较这些字典就可以得到结果。同时,它还检查数据的类型

因此,前两个文件之间的比较将为true,而与第三个文件的比较将返回false

但是您可以始终禁用类型检查,在这种情况下,我们只检查[A,B,C]是否与[A,C,B]相同,而不比较它们的类型。

您可以尝试重新索引:excel2=excel2.reindexcolumns=excel1.columns,其中excel1和excel2分别是读取excel文件1和2后的数据帧吗
{'A': dtype('int64'),
 'C': dtype('int64'),
 'B': dtype('int64')}
{'A': dtype('int64'),
 'B': dtype('int64'),
 'C': dtype('int64'),
 'A.1': dtype('int64'),
 'B.1': dtype('int64'),
 'C.1': dtype('int64')}