[英]Python Pandas GroupBy equivalent of If A and not B where clause in SQL
I am using pandas
groupby
and was wondering how to implement the following: 我正在使用pandas
groupby
,想知道如何实现以下功能:
Dataframes A and B have the same variable to index on, but A has 20 unique index values and B has 5. 数据框A和B具有相同的变量以进行索引,但数据框A具有20个唯一索引值,数据框B具有5个索引值。
I want to create a dataframe C that contains rows whose indices are present in A and not in B. 我想创建一个数据框C,其中包含其索引在A中而不在B中存在的行。
Assume that the 5 unique index values in B are all present in A. C in this case would have only those rows associated with index values in A and not in B (ie 15). 假设B中的5个唯一索引值都存在于A中。在这种情况下,C仅具有那些与A中的索引值相关联的行,而没有与B中的索引值相关联(即15)。
Using inner, outer, left and right do not do this (unless I misread something). 不要使用内部,外部,左侧和右侧(除非我误读了一些内容)。
In SQL I might do this as where A.index <> (not equal) B.index
在SQL中,我可能这样做是where A.index <> (not equal) B.index
My Left handed solution: 我的左手解决方案:
a) get the respective index columns from each data set, say x and y. a)从每个数据集中获得相应的索引列,例如x和y。
def match(x,y,compareCol): 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) now do a left join on this on the data set A. b)现在对数据集A进行左连接。
I am reasonably confident that my elementwise comparison is slow as a tortoise on weed with no motivation. 我有理由相信,我的元素比较作为杂草上的乌龟没有任何动机,会比较缓慢。
What about something like: 怎么样呢?
A.ix[A.index - B.index]
A.index - B.index
is a set
difference: 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.