我有一个熊猫数据帧,如下所示:
first second
0 True False
1 False True
2 True True
3 False False
4 False True
5 False True
6 True False
7 False False
可以用以下代码创建:
import pandas as pd
df = pd.DataFrame(
{
'first': [True, False, True, False, False, False, True, False],
'second': [False, True, True, False, True, True, False, False]
}
)
对于在第一列中具有True
值的任何行,我希望在接下来的行中找到第二列的值为True
的第一行。
所以输出应该是:
first second
1 False True
4 False True
此外,我的首要任务是不使用任何for循环。
你知道这件事吗?
您可以使用:
g = df['first'].ne(df['first'].shift()).cumsum().loc[~df['first']]
# or
# g = df['first'].cumsum()[~df['first']]
out = df[df['second']].groupby(g).head(1)
输出:
first second
1 False True
4 False True
中间石斑鱼g
:
1 2
3 4
4 4
5 4
7 6
Name: first, dtype: int64
没有groupby
的另一种方法:
out = (df.loc[df.loc[df.any(axis=1), 'first'].shift(fill_value=False)
.loc[lambda x: x].index])
print(out)
# Output
first second
1 False True
4 False True
注意:它之所以有效,是因为在first
列的两个True值之间,second
列总是有一个True值。
另一种方法:
first_true_idx = df.loc[df['first']].index
second_true_idx = df.loc[df['second']].index
df = df.loc[second_true_idx[list(filter(
lambda x:x>=0, [(second_true_idx > e).tolist().index(True)
if (second_true_idx > e).any() else -1 for e in first_true_idx]))]]
打印(df(:
first second
1 False True
4 False True
我认为它应该适用于任何位置真正的价值观在"秒"基本上,我试图在第二个真正的索引中为第一个真正索引中的每个索引寻找第一个更大的索引。这正是你要问的。