Skip to main content
 首页 » 编程设计

python之从 Pandas DataFrame 中仅过滤掉真实值,返回 (Row,Col) 的元组

2025年05月04日10freeliver54

给定一个像这样的框架:

  a    b     c 
1 True False False 
2 True True False 
3 False True True 

我想得到这样的列表:

[(1,a), (2,a), (2,b), (3,b), (3,c)] 

过滤掉所有为真的值并检索元组 (rowName, colName)

请您参考如下方法:

另一种方法是使用stack:

>>> s = df.stack() 
>>> s[s].index.tolist() 
[(0L, 'a'), (1L, 'a'), (1L, 'b'), (2L, 'b'), (2L, 'c')] 

这是有效的,因为这里的 stack 返回了扁平化的版本:

>>> df.stack() 
0  a     True 
   b    False 
   c    False 
1  a     True 
   b     True 
   c    False 
2  a    False 
   b     True 
   c     True 
dtype: object