Assuming this input:
Date X1 Contract1 X2 Contract2 X3 Contract3
0 1 1 B 10 B 100 A
1 2 2 B 20 B 200 A
2 3 3 C 30 A 300 B
3 4 4 A 40 C 400 B
4 5 5 A 50 C 500 C
And that you want to select the contract "A", use pandas.wide_to_long
and filter the reshaped DataFrame:
out = (pd.wide_to_long(df, i='Date', j='id', stubnames=['X', 'Contract'])
.query('Contract == "A"')
.reset_index('Date')
)
Output:
Date X Contract
id
1 4 4 A
1 5 5 A
2 3 30 A
3 1 100 A
3 2 200 A
And to keep the dates in order:
out = (pd.wide_to_long(df, i='Date', j='id', stubnames=['X', 'Contract'])
.query('Contract == "A"')
.sort_index().reset_index('Date')
)
Output:
Date X Contract
id
3 1 100 A
3 2 200 A
2 3 30 A
1 4 4 A
1 5 5 A
Alternative with lreshape
that will require you to manually provide the column names:
target = 'A'
out = (pd.lreshape(df, {'X': ['X1', 'X2', 'X3'],
'ContractID': ['Contract1', 'Contract2', 'Contract3']})
.query('ContractID == @target')
.sort_values(by='Date')
)
Output:
Date X ContractID
10 1 100 A
11 2 200 A
7 3 30 A
3 4 4 A
4 5 5 A