A convenience function based on behzad.nouri's commend and cs95's earlier answer. Any errors or misunderstandings are mine.
import pandas as pd import numpy as np df = pd.DataFrame([["2022-01-01", np.nan, np.nan, 1], ["2022-01-02", 2, np.nan, 2], ["2022-01-03", 3, 3, 3], ["2022-01-04", 4, 4, 4], ["2022-01-05", np.nan, 5, 5]], columns=['date', 'A', 'B', 'C']) df['date'] = pd.to_datetime(df['date']) df # date A B C #0 2022-01-01 NaN NaN 1.0 #1 2022-01-02 2.0 NaN 2.0 #2 2022-01-03 3.0 3.0 3.0 #3 2022-01-04 4.0 4.0 4.0 #4 2022-01-05 NaN 5.0 5.0
We want to start at the earliest date common to A and B and end at the latest date common to A and B (for whatever reason, we do not filter by column C).
# filter data to minimum/maximum common available dates def get_date_range(df, cols): """return a tuple of the earliest and latest valid data for all columns in the list""" a,b = df[cols].apply(pd.Series.first_valid_index).max(), df[cols].apply(pd.Series.last_valid_index).min() return (df.loc[a, 'date'], df.loc[b, 'date']) a,b = get_date_range(df, cols=['A', 'B']) a #Timestamp('2022-01-03 00:00:00') b #Timestamp('2022-01-04 00:00:00')
Now filter the data:
df.loc[(df.date >= a) & (df.date <= b)] # date A B C #2 2022-01-03 3.0 3.0 3 #3 2022-01-04 4.0 4.0 4