I'm trying to take one dataframe and create another, with all possible combinations of the columns and the difference between the corresponding values, i.e on 11-apr column AB should be (B-A)= 0 etc.
e.g, starting with
Dt A B C D
11-apr 1 1 1 1
10-apr 2 3 1 2
how do I get a new frame that looks like this:
I have come across the below post, but have not been able to transpose this to work for columns.
Aggregate all dataframe row pair combinations using pandas
Joining two DataFrames can be done in multiple ways (left, right, and inner) depending on what data must be in the final DataFrame.
By use + operator simply you can combine/merge two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.
DataFrame - unstack() functionPivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels.
You can use:
from itertools import combinations
df = df.set_index('Dt')
cc = list(combinations(df.columns,2))
df = pd.concat([df[c[1]].sub(df[c[0]]) for c in cc], axis=1, keys=cc)
df.columns = df.columns.map(''.join)
print (df)
AB AC AD BC BD CD
Dt
11-apr 0 0 0 0 0 0
10-apr 1 -1 0 -2 -1 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With