Ваш ожидаемый результат близок, но я бы создал мультииндекс
, используя melt
и diff
, затем pivot
# melt to get Teams as one columns
melt = df.melt('Date').sort_values('Date')
# groupby and find the difference
melt['diff'] = melt.groupby('value')['Date'].diff()
# pivot to go back to the original df format
melt.pivot('Date','variable')
value diff
variable Team1 Team2 Team1 Team2
Date
2018-06-01 Boston New York NaT NaT
2018-06-13 New York Chicago 12 days NaT
2018-06-27 Boston New York 26 days 14 days
2018-06-28 Chicago Boston 15 days 1 days
Обновление
Здесьобновление для вашего комментария:
# assume this df
Date Team1 Team2
0 2018-06-01 Boston New York
1 2018-06-13 New York Chicago
2 2018-06-27 Boston New York
3 2018-06-28 Chicago Boston
4 2018-06-28 New York Detroit
Код:
# melt df (same as above example)
melt = df.melt('Date').sort_values('Date')
# find the difference
melt['diff'] = melt.groupby('value')['Date'].diff()
# use pivot_table not pivot
piv = melt.pivot_table(index=['Date', 'diff'], columns='variable', values='value', aggfunc=lambda x:x)
# reset index and dropna from team 1
piv.reset_index(level=1, inplace=True)
piv = piv[~piv['Team1'].isna()]
# merge your original df and your new one together
pd.merge(df, piv[piv.columns[:-1]], on=['Date','Team1'], how='outer').fillna(0)
Date Team1 Team2 diff
0 2018-06-01 Boston New York 0 days
1 2018-06-13 New York Chicago 12 days
2 2018-06-27 Boston New York 26 days
3 2018-06-28 Chicago Boston 15 days
4 2018-06-28 New York Detroit 1 days
Обратите внимание, что на этот раз разница только с прошлым разом, когда Team1 играл