我有两个p和as数据帧,ab:

a1   a2   a3   a4   a5   a6   a7
1    3    4    5    3    4    5
0    2    0    3    0    2    1
2    5    6    5    2    1    2

b1   b2   b3   b4   b5   b6   b7
3    5    4    5    1    4    3
0    1    2    3    0    0    2
2    2    1    5    2    6    5

The two data frames contain exactly the same data, but in a different order 和 with different column names. Based on the numbers in the two data frames, I would like to be able to match each column name in a to each column name in b.

It is not as easy as simply comparing the first row of a with the first row of b as there are duplicated values, for example both a4a7 have the value 5 so it is not possible to immediately match them to either b2 or b4.

最好的方法是什么?

推荐答案

这里有一种方法,利用broadcasting来判断两个数据帧之间的相等性,并在结果上取all来判断所有行在哪里匹配.然后我们可以从np.where的结果中获得dataframe两个列名的索引数组(使用@piR的贡献):

i, j = np.where((a.values[:,None] == b.values[:,:,None]).all(axis=0))
dict(zip(a.columns[j], b.columns[i]))
# {'a7': 'b2', 'a6': 'b3', 'a4': 'b4', 'a2': 'b7'}

Python-3.x相关问答推荐

如何从Django连接到Neo4J s AuraDB(免费层)?'

新行是pandas数据帧中旧行的组合

Pandas groupby 然后 for each 组添加新行

转换Pandas 数据框 - 添加行

使用 multiprocessing 处理图像

如何通过 GitLab V4 api 列出 gitlab 项目中的所有项目变量

python 3.10.5 中可能存在的错误. id 函数工作不明确

没有可重定向到的 URL.提供一个 url 或在模型上定义一个 get_absolute_url 方法

预分配一个无列表

为什么 Django South 1.0 使用 iteritems()?

如何模拟 Django 模型对象(及其方法)?

在 Python 3 中使用 unittest.mock 修补 input()

使用逗号时,除了处理程序中的语法无效

如何使 Python3 成为 Geany 中的默认 Python

tkinter TclError:错误的文件类型使用 askopenfilename

将 args、kwargs 传递给 run_in_executor

SQLAlchemy:如果不存在则创建模式

如何将文档字符串放在 Enums 上?

如何修复:cx_Oracle.DatabaseError:DPI-1047:找不到 64 位 Oracle 客户端库 - Python

在 Python 中生成马尔可夫转移矩阵