在 pandas 中获取列为 True 的索引

TL;DR

只需使用

example.py
df[df["ZeroCrossing"]].index

完整示例:

我们将使用我们在上一篇关于如何检测 pandas 字符串列/series 中的值变化的文章中构建的 ZeroCrossing 列,该文章本身基于我们关于如何创建 pandas 时间序列 DataFrame 示例数据集的文章。基于该示例,我们只修改最后一行:

example_full.py
import pandas as pd

# 加载预构建的时间序列示例数据集
df = pd.read_csv("https://techoverflow.net/datasets/timeseries-example.csv", parse_dates=["Timestamp"])
df.set_index("Timestamp", inplace=True)

# 创建包含 "Positive" 或 "Negative" 的新列
df["SinePositive"] = (df["Sine"] >= 0).map({True: "Positive", False: "Negative"})
# 创建 "change" 列(布尔值)
df["ZeroCrossing"] = df["SinePositive"].shift() != df["SinePositive"]
# 将第一个条目设置为 False
df["ZeroCrossing"].iloc[0] = False

# 打印结果
print(df[df["ZeroCrossing"]].index)

这打印

output.txt
DatetimeIndex(['2020-05-25 20:05:10.040874', '2020-05-25 20:05:10.090874',
               '2020-05-25 20:05:10.140874', '2020-05-25 20:05:10.190874',
               '2020-05-25 20:05:10.240874', '2020-05-25 20:05:10.290874',
               '2020-05-25 20:05:10.340874', '2020-05-25 20:05:10.390874',
               '2020-05-25 20:05:10.440774', '2020-05-25 20:05:10.490874',
               '2020-05-25 20:05:10.540874', '2020-05-25 20:05:10.590874',
               '2020-05-25 20:05:10.640774', '2020-05-25 20:05:10.690874',
               '2020-05-25 20:05:10.740874', '2020-05-25 20:05:10.790874',
               '2020-05-25 20:05:10.840874', '2020-05-25 20:05:10.890774',
               '2020-05-25 20:05:10.940874'],
              dtype='datetime64[ns]', name='Timestamp', freq=None)

Check out similar posts by category: Pandas, Python