【问题标题】:How to get true values and flanking falses in columns如何在列中获取真值和侧翼假值
【发布时间】:2018-11-09 12:02:18
【问题描述】:

我想知道如何最简单的方法是选择列中的所有 True 行以及一组 True 中紧邻的 False 行。

TLDR;提取所有为 True 的行以及上面的 False 行 1, 每个 True 行下方 1 个。

这就是我的意思:

df

0     False
1     False
2      True
3      True
4     False
5     False
6     False
7     False
8      True
9      True
10     True
11    False
12    False
13    False
14    False
15     True
16     True
dtype: bool

那么,运行代码后,结果会是:

result:

1   False
2   True
3   True
4   False
7   False
8   True
9   True
10  True
11  False
14  False
15  True
16  True

【问题讨论】:

  • 输出中没有0 False的任何原因?
  • 我不清楚你在问什么,尽管我使用 jez answer 声明了可能的 dup。
  • 因此,他们想要所有 True 值,以及正上方和正下方的 False-y 值。
  • 我不知道为什么 jezrael 的回答被否决@jezrael 而其他人的回答几乎相同?
  • @Wen 不是我。但我认为与目前的答案相比,它可能有点矫枉过正。

标签: python pandas boolean slice


【解决方案1】:

我认为这是需要的:

import pandas as pd

df = pd.DataFrame({'value': [
    False,
    False,
    True,
    True,
    False,
    False,
    False,
    False,
    True,
    True,
    True,
    False,
    False,
    False,
    False,
    True,
    True,
]})

result = df[df.value | df.value.shift(-1) | df.value.shift(1)]
print(result)

输出:

    value
1   False
2    True
3    True
4   False
7   False
8    True
9    True
10   True
11  False
14  False
15   True
16   True

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 2019-08-20
    • 2013-10-13
    • 2022-07-05
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2016-02-18
    相关资源
    最近更新 更多