Get index where column is True in pandas
TL;DR
Simply use
df[df["ZeroCrossing"]].index
Full example:
We’ll use the ZeroCrossing
column we built in our previous post on How to detect value change in pandas string column/series which itself builds on our post on How to create pandas time series DataFrame example dataset. Based on that example, we only modify the last line:
import pandas as pd
# Load pre-built time series example dataset
df = pd.read_csv("https://techoverflow.net/datasets/timeseries-example.csv", parse_dates=["Timestamp"])
df.set_index("Timestamp", inplace=True)
# Create a new column containing "Positive" or "Negative"
df["SinePositive"] = (df["Sine"] >= 0).map({True: "Positive", False: "Negative"})
# Create "change" column (boolean)
df["ZeroCrossing"] = df["SinePositive"].shift() != df["SinePositive"]
# Set first entry to False
df["ZeroCrossing"].iloc[0] = False
# Print result
print(df[df["ZeroCrossing"]].index)
This prints
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)