如何解决检查熊猫数据框中的值对是否不相同
我有熊猫数据框形式的数据集,如下:
在此数据集中,我想查找那些值不相同的名称和值。它也应适用于非平方矩阵。示例:
A to B is 4. So,B to A must be 4. But B to A is 8.
A to C is 5. So,C to A must be 5. OK.
A to D is 8. So,D to A must be 8. But D to A is 5.
B to C is 6. So,C to B must be 6. But C to B is 3.
and so on...
所以,要输出为:
(A,B,4) and (B,A,8)
(A,D,8) and (D,5)
(B,C,6) and (C,3)
在相同的值处不打印。 我正在尝试使用numpy数组和字典,但无法弄清楚确切的逻辑。
解决方法
这是使用熊猫的方法
data = {'A':[0,8,5,1],'B':[4,3,7,2],'C':[5,6,4,3],'D':[8,9,2,4],'F':[7,1]}
tdf = pd.DataFrame(data,index=['A','B','C','D','E'])
for idx in tdf.index:
if idx in tdf.columns:
for col in tdf.columns:
if col in tdf.index and col != idx and tdf[idx][col] != tdf[col][idx]:
print (f'({idx},{col},{tdf[idx][col]}) and ({col},{idx},{tdf[col][idx]})' )
tdf:
A B C D F
A 0 4 5 8 7
B 8 0 6 9 5
C 5 3 0 2 6
D 5 7 4 0 2
E 1 2 3 4 1
,输出格式为:
(A,B,8) and (B,A,4)
(A,D,5) and (D,8)
(B,4) and (A,C,3) and (C,6)
(B,7) and (D,9)
(C,6) and (B,3)
(C,4) and (D,2)
(D,8) and (A,5)
(D,9) and (B,7)
(D,2) and (C,4)
,
感谢@ itprorh66提供的数据制作数据框:
df = pd.DataFrame({'A':[0,1]},'E'])
相交并创建一个方形数据框。
cmg = df.index.intersection(df.columns)
df = df[cmg].loc[cmg]
我们可以使用numpy的上下三角函数,并拔出上三角的索引:
mat = df.to_numpy()
tr = np.triu_indices(len(cmg),k=1)
然后将所有内容放入一个数据帧中,行名和列名的连接有点微不足道,但这就是我目前能做的最好的事情:
mat = df.to_numpy()
tr = np.triu_indices(len(cmg),k=1)
match_tri = pd.DataFrame({'i1':df.index[tr[0]] + ',' + df.columns[tr[1]],'v1':mat[tr],'i2':df.index[tr[1]] + ',' + df.columns[tr[0]],'v2':mat.T[tr]
})
然后,我们仅根据值进行子集化:
match_tri[match_tri.v1 != match_tri.v2]
i1 v1 i2 v2
0 A,B 4 B,A 8
2 A,D 8 D,A 5
3 B,C 6 C,B 3
4 B,D 9 D,B 7
5 C,D 2 D,C 4
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。