在数据帧列中查找最后一个匹配值

问题描述 投票:0回答:4

我有一个带有“状态”列的数据框,其值: 真的, 错误的, 错误的, 真的, 正确

我想找到 False 的最后一个位置并获取仅包含最后两个值的数据帧。

python pandas dataframe filter find
4个回答
2
投票
import pandas as pd

# dataframe as you described
df = pd.DataFrame({
    'status' : [True, False, False, True, True]
})

# get the row number of the last False (credit to mozway for index idea)
last_false = df.index[~df['status']].max()

# get every row after the last false
df.loc[last_false+1:]

# or just getting the last two rows
df.tail(2)

2
投票

使用

idxmax
shift
的一个选项可以避免依赖范围索引:

df.iloc[df.loc[::-1, 'status'].shift(-1).eq(False).idxmax():]

输出:

   status
3    True
4    True

1
投票

Series.mask
+
Series.last_valid_index
:

df.iloc[df['status'].mask(df['status']).last_valid_index() + 1:]

   status
3    True
4    True

0
投票

使用

index

的另一个选项
import pandas as pd

data = {
    "status": [True, False, False, True, True]
}

df = pd.DataFrame(data)
val = df[df['status'] == False].index[-1]
df_final = df.iloc[val+1:,:]
print(df_final)

status
3    True
4    True
© www.soinside.com 2019 - 2024. All rights reserved.