Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

python - Getting (index, column) pairs for True elements of a boolean DataFrame in Pandas

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

Is there any way to obtain:

x.loc[y]

To return:

[(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))

But I imagine something better may be possible / already implemented. In matlab the function find combined with sub2ind do the job.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
x[x > 0].stack().index.tolist()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...