繁体   English   中英

熊猫逻辑运算

[英]Pandas logical operation

我遇到了熊猫19.2的问题,无法给我期望的结果。 列ag具有['yes','no','',NaN]。 如果这些列中的任何一个为“是”,我希望返回该行(还有其他未显示的列)。 这是我的代码。

xdf2  =  xdf[((xdf['a'] == 'yes').all() or 
                    (xdf['b'] == 'yes').all() or 
                    (xdf['c'] == 'yes').all() or 
                    (xdf['d'] == 'yes' ).all() or
                    (xdf['e'] == 'yes').all() or 
                    (xdf['f'] == 'yes').all() or  
                    (xdf['g'] =='yes').all()) ]

这给了我以下错误:

   2134                 return self._engine.get_loc(key)
   2135             except KeyError:
-> 2136                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2137 
   2138         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)()

pandas\src\hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)()

pandas\src\hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)()

KeyError: False

没有“ .all”,我得到

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这似乎是一个简单且通用的代码段,但是我还没有找到一个很好的例子。 我想念什么?

尝试

xdf[xdf[list('abcdefg')].eq('yes').any(1)]

以下应该工作:

import pandas as pd

a = [["yes", "no", "yes", "yes"],
     ["yes", "yes", "no", "yes"],
     ["yes", "no", "yes", "yes"]]
xdf = pd.DataFrame(a, columns=["a", "b", "c", "d"])     
print xdf

boollist = [ (xdf[col] == "yes").all() for col in xdf.columns ]
xdf2  =  xdf[xdf.columns[boollist] ]
print xdf2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM