<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def weighted_expiration(weights, contract_dates):
 """ Calculate the days to expiration for generic futures, weighted by the composition of the underlying tradeable instruments. Parameters: weights: pandas.DataFrame A DataFrame of instrument weights with a MultiIndex where the top level contains pandas.Timestamps and the second level is instrument names. The columns consist of generic names. contract_dates: pandas.Series Series with index of tradeable contract names and pandas.Timestamps representing the last date of the roll as values Returns: -------- A pandas.DataFrame with columns of generic futures and index of dates. Values are the weighted average of days to expiration for the underlying contracts. Examples: --------- """
  # NOQA
    cols = weights.columns
    weights = weights.reset_index(level=-1)
    expiries = contract_dates.to_dict()
    weights.loc[:, "expiry"] = weights.iloc[:, 0].apply(lambda x: expiries[x])
    diffs = (pd.DatetimeIndex(weights.expiry)
             - pd.Series(weights.index, weights.index)).apply(lambda x: x.days)
    weights = weights.loc[:, cols]
    wexp = weights.mul(diffs, axis=0).groupby(level=0).sum()
    return wexp