【发布时间】: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)
【问题讨论】:
-
好的。你试过什么?
给定这样的框架:
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
【讨论】:
df[df].stack().index.tolist() 中完成此操作。 df[df] 虽然比 s[s] 慢得多。
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')]
【讨论】: