Python Pandas - 基于先前获取的子集从DataFrame中删除行

DMM*_*MML 12 python pandas

我运行Python 2.7Pandas 0.11.0安装的库.

我一直在寻找一个没有找到这个问题的答案,所以我希望有人比我有解决方案更有经验.

让我们说我的数据,在df1中,如下所示:

df1=

  zip  x  y  access
  123  1  1    4
  123  1  1    6
  133  1  2    3
  145  2  2    3
  167  3  1    1
  167  3  1    2
Run Code Online (Sandbox Code Playgroud)

例如,使用df2 = df1[df1['zip'] == 123]然后df2 = df2.join(df1[df1['zip'] == 133])我得到以下数据子集:

df2=

 zip  x  y  access
 123  1  1    4
 123  1  1    6
 133  1  2    3
Run Code Online (Sandbox Code Playgroud)

我想做的是:

1)从df1定义/连接时删除行df2

要么

2)df2创建完成后,删除df1由其df2组成的行(差异?)

希望所有这一切都有道理.如果需要更多信息,请告诉我.

编辑:

理想情况下,第三个数据框将是创建的,如下所示:

df2=

 zip  x  y  access
 145  2  2    3
 167  3  1    1
 167  3  1    2
Run Code Online (Sandbox Code Playgroud)

也就是说,一切都df1从不存在df2.谢谢!

DSM*_*DSM 26

我想到了两种选择.首先,使用isin和面具:

>>> df
   zip  x  y  access
0  123  1  1       4
1  123  1  1       6
2  133  1  2       3
3  145  2  2       3
4  167  3  1       1
5  167  3  1       2
>>> keep = [123, 133]
>>> df_yes = df[df['zip'].isin(keep)]
>>> df_no = df[~df['zip'].isin(keep)]
>>> df_yes
   zip  x  y  access
0  123  1  1       4
1  123  1  1       6
2  133  1  2       3
>>> df_no
   zip  x  y  access
3  145  2  2       3
4  167  3  1       1
5  167  3  1       2
Run Code Online (Sandbox Code Playgroud)

二,使用方法groupby:

>>> grouped = df.groupby(df['zip'].isin(keep))
Run Code Online (Sandbox Code Playgroud)

然后任何一个

>>> grouped.get_group(True)
   zip  x  y  access
0  123  1  1       4
1  123  1  1       6
2  133  1  2       3
>>> grouped.get_group(False)
   zip  x  y  access
3  145  2  2       3
4  167  3  1       1
5  167  3  1       2
>>> [g for k,g in list(grouped)]
[   zip  x  y  access
3  145  2  2       3
4  167  3  1       1
5  167  3  1       2,    zip  x  y  access
0  123  1  1       4
1  123  1  1       6
2  133  1  2       3]
>>> dict(list(grouped))
{False:    zip  x  y  access
3  145  2  2       3
4  167  3  1       1
5  167  3  1       2, True:    zip  x  y  access
0  123  1  1       4
1  123  1  1       6
2  133  1  2       3}
>>> dict(list(grouped)).values()
[   zip  x  y  access
3  145  2  2       3
4  167  3  1       1
5  167  3  1       2,    zip  x  y  access
0  123  1  1       4
1  123  1  1       6
2  133  1  2       3]
Run Code Online (Sandbox Code Playgroud)

哪个最有意义取决于上下文,但我认为你明白了.