Python Pandas GroupBy 相当于 SQL 中的 If A and not B where 子句

标签 python sql group-by pandas

我正在使用pandas groupby并想知道如何实现以下内容:

  1. 数据帧 A 和 B 有相同的索引变量,但 A 有 20 个唯一索引值,B 有 5 个。

  2. 我想创建一个数据帧 C,其中包含索引存在于 A 中而不是 B 中的行。

  3. 假设 B 中的 5 个唯一索引值都存在于 A 中。在这种情况下,C 将仅包含与 A 中的索引值相关联的行,而不是 B 中的索引值(即 15)。

  4. 使用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/

相关文章:

python - pysvn 给出错误 : Not a working copy

python - 在 BigQuery API 中使用标准 SQL 时出现 BigQuery 无效表名错误

javascript - 如何使用/从 python 字典发送键()

SQL OpenXML 多标签问题

mysql - 跨列按 id 分组

python - 如何获取 python-chess 模块中所有合法移动的列表?

SQL 到 Excel 丢失尾随零

sql - LIKE 和 ~ 在 Postgres 中的区别

mysql - 如何查找具有相似字符串部分的重复行

python - Pandas - 根据多种条件更新列 - 按方法分组