![](/img/trans.png)
[英]Python - count number of elements that are equal between two columns of two dataframes
[英]Find equal columns between two dataframes
我有兩個pandas
數據框a
和b
:
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
這兩個數據框包含完全相同的數據,但順序不同,列名也不同。 根據兩個數據框中的數字,我希望能夠將a
中的每個列名與b
中的每個列名相匹配。
這並不像簡單地將a
的第一行與b
的第一行進行比較那么容易,因為存在重復值,例如a4
和a7
都具有值5
因此不可能立即將它們與b2
或b4
匹配。
做這個的最好方式是什么?
這是使用sort_values
一種方法:
m=df1.T.sort_values(by=[*df1.index]).index
n=df2.T.sort_values(by=[*df2.index]).index
d=dict(zip(m,n))
print(d)
{'a1': 'b5', 'a5': 'b1', 'a2': 'b7', 'a3': 'b6', 'a6': 'b3', 'a7': 'b2', 'a4': 'b4'}
一種merge
s=df1.T.reset_index().merge(df2.T.assign(match=lambda x : x.index))
dict(zip(s['index'],s['match']))
{'a1': 'b5', 'a2': 'b7', 'a3': 'b6', 'a4': 'b4', 'a5': 'b1', 'a6': 'b3', 'a7': 'b2'}
使用列值的tuple
作為字典中的可散列鍵
d = {(*t,): c for c, t in df2.items()}
{c: d[(*t,)] for c, t in df1.items()}
{'a1': 'b5',
'a2': 'b7',
'a3': 'b6',
'a4': 'b4',
'a5': 'b1',
'a6': 'b3',
'a7': 'b2'}
以防萬一我們沒有完美的表示,我只為有匹配的列生成了字典。
d2 = {(*t,): c for c, t in df2.items()}
d1 = {(*t,): c for c, t in df1.items()}
{d1[c]: d2[c] for c in {*d1} & {*d2}}
{'a5': 'b1',
'a2': 'b7',
'a7': 'b2',
'a6': 'b3',
'a3': 'b6',
'a1': 'b5',
'a4': 'b4'}
idxmax
這幾乎是荒謬的......實際上不要這樣做。
{c: df2.T.eq(df1[c]).sum(1).idxmax() for c in df1}
{'a1': 'b5',
'a2': 'b7',
'a3': 'b6',
'a4': 'b4',
'a5': 'b1',
'a6': 'b3',
'a7': 'b2'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.