您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – Pandas中SQL中EXCEPT子句的类比是什么?

5b51 2022/1/14 8:22:15 python 字数 2815 阅读 549 来源 www.jb51.cc/python

我有一个示例pandas dataframe df: col1 col2 col3 col4 0 a 1.0 2.0 3 1 b NaN NaN 6 2 c NaN 8.0 9 3 d NaN 11.0 12

概述

col1    col2    col3    col4
      0   a      1.0    2.0      3
      1   b      NaN    NaN      6
      2   c      NaN    8.0      9
      3   d      NaN    11.0    12
      4   e     13.0    14.0    15
      5   f     17.0    18.0    19
      6   g     21.0    22.0    23

和第二个df1:

col1    col2    col3    col4
      0  a      1.0     2.0      3
      4  e     13.0    14.0     15
      5  f     17.0    18.0     19
      6  g     21.0    22.0     23

我想获得与df1不重叠的df子集.实际上我在sql中寻找等效的EXCEPT操作数.

我使用了subtract()函数 – 但这显然是错误的,因为减法执行元素数字减法.所以我收到一条错误消息:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

所以问题是:在Pandas的sql中,EXCEPT的等价物是什么?

df2 = df.set_index('col1').subtract(df1.set_index('col1'),axis='columns')
print (df2)
      col2  col3  col4
col1                  
a      0.0   0.0   0.0
b      NaN   NaN   NaN
c      NaN   NaN   NaN
d      NaN   NaN   NaN
e      0.0   0.0   0.0
f      0.0   0.0   0.0
g      0.0   0.0   0.0

要么:

df2 = df.set_index('col1').subtract(df1.set_index('col1'),axis='columns',fill_value=0)
print (df2)
      col2  col3  col4
col1                  
a      0.0   0.0   0.0
b      NaN   NaN   6.0
c      NaN   8.0   9.0
d      NaN  11.0  12.0
e      0.0   0.0   0.0
f      0.0   0.0   0.0
g      0.0   0.0   0.0

编辑问题编辑:

print (df.isin(df1))
    col1   col2   col3   col4
0   True   True   True   True
1  False  False  False  False
2  False  False  False  False
3  False  False  False  False
4   True   True   True   True
5   True   True   True   True
6   True   True   True   True

print (df.isin(df1).all(axis=1))
0     True
1    False
2    False
3    False
4     True
5     True
6     True
dtype: bool

print (~df.isin(df1).all(axis=1))
0    False
1     True
2     True
3     True
4    False
5    False
6    False
dtype: bool

print (df[~(df.isin(df1).all(axis=1))])
  col1  col2  col3  col4
1    b   NaN   NaN     6
2    c   NaN   8.0     9
3    d   NaN  11.0    12

总结

以上是编程之家为你收集整理的python – Pandas中SQL中EXCEPT子句的类比是什么?全部内容,希望文章能够帮你解决python – Pandas中SQL中EXCEPT子句的类比是什么?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶