在 pandas 中获取布尔数据框的True元素的(索引,列)对 [英] Getting (index, column) pairs for True elements of a boolean DataFrame in Pandas
本文介绍了在 pandas 中获取布尔数据框的True元素的(索引,列)对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个Pandas DataFrame,我想获取一个格式为[[index1,column1),(index2,column2)...]的元组列表,该列表描述了DataFrame的所有元素在某些情况下的位置真的.例如:
Say I have a Pandas DataFrame and I want to obtain a list of tuples of the form [(index1, column1), (index2, column2) ...] describing the locations of all elements of the DataFrame where some condition is true. For example:
x = pd.DataFrame(np.random.normal(0, 1, (4,4)), index=['a', 'b', 'c', 'd'],
columns=['e', 'f', 'g', 'h'])
x
e f g h
a -1.342571 -0.274879 -0.903354 -1.458702
b -1.521502 -1.135800 -1.147913 1.829485
c -1.199857 0.458135 -1.993701 -0.878301
d 0.485599 0.286608 -0.436289 -0.390755
y = x > 0
有什么方法可以获取:
x.loc[y]
要返回:
[(b, h), (c,f), (d, e), (d,f)]
还是一些等效的?显然,我可以做到:
Or some equivalent? Evidently, I can do:
postup = []
for i in x.index:
for j in x.columns:
if x.loc[i, j] > 0:
postup.append((i, j))
但是我想可能有一些更好的事情/已经实施.在matlab中,将功能find与sub2ind结合在一起即可完成工作.
But I imagine something better may be possible / already implemented. In matlab the function find combined with sub2ind do the job.
推荐答案
x[x > 0].stack().index.tolist()
这篇关于在 pandas 中获取布尔数据框的True元素的(索引,列)对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文