【问题标题】:How to do logical operation between DataFrame and Series?DataFrame和Series之间如何进行逻辑运算?
【发布时间】:2016-10-02 16:48:59
【问题描述】:

假设我有一个 bool DataFrame df 和一个 bool Series x 具有相同的索引,并且我想在每列 dfx 之间进行逻辑运算。与使用DataFrame.apply相比,有没有像DataFrame.sub这样的快捷方式?

In [31]: df
Out[31]: 
       x      y      z      u
A  False  False   True   True
B   True   True   True   True
C   True  False  False  False

In [32]: x
Out[32]: 
A     True
B    False
C     True
dtype: bool

In [33]: r = df.apply(lambda col: col & x) # Any other way ??

In [34]: r
Out[34]: 
       x      y      z      u
A  False  False   True   True
B  False  False  False  False
C   True  False  False  False

【问题讨论】:

    标签: python pandas dataframe boolean logical-operators


    【解决方案1】:

    使用mul,但需要先转换为int,然后再转换为bool,因为UserWarning

    print (df.astype(int).mul(x.values, axis=0).astype(bool))
           x      y      z      u
    A  False  False   True   True
    B  False  False  False  False
    C   True  False  False  False
    

    类似的解决方案:

    print (df.mul(x.astype(int), axis=0).astype(bool))
           x      y      z      u
    A  False  False   True   True
    B  False  False  False  False
    C   True  False  False  False
    

    print (df.mul(x.values, axis=0))
           x      y      z      u
    A  False  False   True   True
    B  False  False  False  False
    C   True  False  False  False
    

    C:\Anaconda3\lib\site-packages\pandas\computation\expressions.py:181: UserWarning: 在 Python 空间中进行评估,因为 numexpr 不支持 bool dtype 的 '*' 运算符,请使用 '&'反而 不支持[op_str]))

    np.logical_and 的另一个 numpy 解决方案:

    print (pd.DataFrame(np.logical_and(df.values, x.values[:, None]), 
                                       index=df.index, 
                                       columns=df.columns))
    
           x      y      z      u
    A  False  False   True   True
    B  False  False  False  False
    C   True  False  False  False
    

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多