Python Pandas GroupBy相当于SQL中的If A而不是B where子句

2024-03-28 19:06:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandasgroupby,想知道如何实现以下功能:

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

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

  3. 假设B中的5个唯一索引值都存在于A中。在这种情况下,A中只有那些与索引值相关联的行,而B中没有(即15个)。

  4. 使用“内”、“外”、“左”和“右”不要这样做(除非我读错了什么)。

在SQL中,我可以这样做where A.index <> (not equal) B.index

我的左手解决方案:

a)从每个数据集中获取相应的索引列,比如x和y

定义匹配(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执行左连接

我有理由相信,我的元素比较是缓慢的,就像乌龟在杂草上没有 动机。在


Tags: andtheto数据nameinnewindex