【问题标题】:Filtering out only true values from Pandas DataFrame, return tuples of (Row,Col)从 Pandas DataFrame 中仅过滤掉真值,返回 (Row,Col) 的元组
【发布时间】:2014-04-13 10:01:02
【问题描述】:

给定这样的框架:

  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)

【问题讨论】:

  • 好的。你试过什么?

标签: python pandas


【解决方案1】:

另一种方法是使用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

【讨论】:

  • 看起来总是那么简单:)
  • 您甚至可以在一行df[df].stack().index.tolist() 中完成此操作。 df[df] 虽然比 s[s] 慢得多。
【解决方案2】:
In [27]: df
Out[27]: 
       a      b      c
1   True  False  False
2   True   True  False
3  False   True   True

[3 rows x 3 columns]

您可以使用np.where 找到与Trues 对应的索引:

In [28]: np.where(df)
Out[28]: (array([0, 1, 1, 2, 2]), array([0, 0, 1, 1, 2]))

In [29]: x, y = np.where(df)

索引和列都是ndarrays,你可以使用NumPy整数索引来选择标签:

In [30]: df.index[y]
Out[30]: Int64Index([1, 1, 2, 2, 3], dtype='int64')

In [31]: df.columns[x]
Out[31]: Index([u'a', u'b', u'b', u'c', u'c'], dtype='object')

zip放在一起:

In [32]: zip(df.index[y], df.columns[x])
Out[32]: [(1, 'a'), (1, 'b'), (2, 'b'), (2, 'c'), (3, 'c')]

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 2016-01-06
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2012-10-21
    • 2017-08-24
    相关资源
    最近更新 更多