【发布时间】:2019-07-31 01:53:01
【问题描述】:
我想寻找有效的方法来查找满足数据框中某些条件的行。
数据框有 n 行和 3 列。值为-1 或0 或1。
我想找到满足两个条件的行。
- 条件:行的值(row0) !=-1;
- 条件:接下来3行(row1,row2,row3)生成的数组的对角线=1。
我使用循环方法遍历所有行并找到满足条件的行。但是,这不是一种有效的方法,尤其是当有一个大数据框并且这一步只是第一步时。
# Given a dataframe (n*3)
randNum=random.choices(range(-1,2),k=333) # k=3*int
frame=pd.DataFrame(np.array(randNum).reshape(-1,3))
# its values = -1,0,1, like this:
# In [126]:frame
# Out[126]:
# 0 1 2
# 0 1 0 0
# 1 1 -1 1
# 2 1 1 1
# 3 -1 -1 1
# 4 -1 0 -1
# 5 1 1 -1
# ...
# 105 -1 -1 -1
# 106 -1 -1 0
# 107 -1 -1 0
# 108 0 -1 1
# 109 -1 0 1
# 110 1 0 1
# I want find the row(s) that all of the values of
# columns('0','1','2')!=-1, and while the value of
# the diagonal of next three rows =1, like this:
# 0 1 2
# row0 v1 v2 v3 # v1!=v2!=v3!=-1, it may be 1 or 0.
# row1 1 v v
# row2 v 1 v # v =-1 or 0 or 1
# row3 v v 1
# the diagonal of rows (row1,row2,row3)=1
我想在 DataFrame 中找到第 0 行。它可以通过循环方法解决,但是否存在有效的解决方案?非常感谢!
【问题讨论】:
标签: python python-3.x pandas numpy dataframe