簡體   English   中英

Python Pandas GroupBy與SQL中的If A和not B where子句等效

[英]Python Pandas GroupBy equivalent of If A and not B where clause in SQL

我正在使用pandas groupby ,想知道如何實現以下功能:

  1. 數據框A和B具有相同的變量以進行索引,但數據框A具有20個唯一索引值,數據框B具有5個索引值。

  2. 我想創建一個數據框C,其中包含其索引在A中而不在B中存在的行。

  3. 假設B中的5個唯一索引值都存在於A中。在這種情況下,C僅具有那些與A中的索引值相關聯的行,而沒有與B中的索引值相關聯(即15)。

  4. 不要使用內部,外部,左側和右側(除非我誤讀了一些內容)。

在SQL中,我可能這樣做是where A.index <> (not equal) B.index

我的左手解決方案:

a)從每個數據集中獲得相應的索引列,例如x和y。

def match(x,y,compareCol):

"""

x and y are series

compare col is the name to the series being returned .

It is the same name as the name of x and y in their respective dataframes"""

x = x.unique()

y = y.unique()

""" Need to compare arrays x.unique() returns arrays"""

new = []

for item in (x):

    if item not in y:

        new.append(item)

returnADataFrame = pa.DataFrame(pa.Series(new, name = compareCol))

return returnADataFrame

b)現在對數據集A進行左連接。

我有理由相信,我的元素比較作為雜草上的烏龜沒有任何動機,會比較緩慢。

怎么樣呢?

A.ix[A.index - B.index]

A.index - B.index是一個set差異:

    In [30]: A.index
    Out[30]: Int64Index([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], dtype=int64)

    In [31]: B.index
    Out[31]: Int64Index([  0,   1,   2,   3, 999], dtype=int64)

    In [32]: A.index - B.index
    Out[32]: Int64Index([ 4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], dtype=int64)

    In [33]: B.index - A.index
    Out[33]: Int64Index([999], dtype=int64)

暫無
暫無

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

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