簡體   English   中英

檢查嵌套分區中的行具有相同的值

[英]Check rows within a nested partition have the same values

我有一個帶有兩個ID的表,我需要檢查特定的ID1和ID2,所有產品是否相同且產品數量相同。

例如,在下表中,我有10001,其中有123和234,並且缺少一行,其中有產品2和123。

對於20002,345和456都有產品3和4,但是最后一個產品有所不同。 我需要在數據中找到這種情況。

ID1     ID2     Product
10001   123     Product 1
10001   234     Product 1
10001   234     Product 2
20002   345     Product 3
20002   345     Product 4
20002   345     Product 5
20002   456     Product 3
20002   456     Product 4
20002   456     Product 6

完美的場景將會是正確的。

ID1     ID2     Product
10001   123     Product 1
10001   123     Product 2
10001   234     Product 1
10001   234     Product 2
20002   345     Product 3
20002   345     Product 4
20002   345     Product 5
20002   456     Product 3
20002   456     Product 4
20002   456     Product 5

基本上,我需要在我的數據中查找所有情況,其中在特定的ID1中,所有ID2都沒有一致的乘積,通過一致的乘積,我的意思是所有ID2在ID1中都應具有相同的乘積。

在第一個表中找到病例的方法有什么建議嗎? 謝謝!

想象一下,您已經將數據加載到dict中,並且產品列表是一個集合(順便說一句,這將幫助您確保產品不會重復復制為id1,id2):

data = {
    10001: {
        123: set([1]),
        234: set([1,2])
    },
    20002: {
        345: set([3,4,6]),
        456: set([3,4,6])
    }
}

然后,您可以通過在集合上使用“ ^”運算符來檢查id2的兩個值是否具有相同的項目。 檢查https://docs.python.org/3/library/stdtypes.html#set 例如:

a = data[10001][123]
b = data[10001][234]
c = a ^ b # len(c) will be >0 !!

'^'計算兩個集合之間的對稱差,因此僅當兩個集合相等時,它將返回空集合。

因此,您可以遍歷給定id1的所有id2密鑰,並在出現“ ^”且上一個密鑰沒有達到len時中斷一條消息。 例:

for id1 in data:
    last_seen = None
    for id2 in data[id1]:
        actual = data[id1][id2]
        if last_seen != None and len(last_seen ^ actual) != 0:
                print('Items for id1 {} are not equal'.format(id1))
                break
        last_seen = actual

這是假設您的csv文件沒有必要進行排序,因此您需要將其加載到字典中...如果您的文件是按id進行排序的,那么您可以立即讀取該文件並完成工作,當然,我敢肯定你可以適應這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM