我正在使用pandas
groupby
并想知道如何实现以下内容:
数据帧 A 和 B 有相同的索引变量,但 A 有 20 个唯一索引值,B 有 5 个。
我想创建一个数据帧 C,其中包含索引存在于 A 中而不是 B 中的行。
假设 B 中的 5 个唯一索引值都存在于 A 中。在这种情况下,C 将仅包含与 A 中的索引值相关联的行,而不是 B 中的索引值(即 15)。
里>使用inner、outer、left和right不会这样做(除非我读错了什么)。
在 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
是一个集合
差异:
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)
关于Python Pandas GroupBy 相当于 SQL 中的 If A and not B where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10767163/