Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pivot table in pandas with a subtraction function on all possible combinations

I have a dataframe that looks something like

Strike. Strike2 Price
15000.  15000.  100
15100.  15100.  150
15200.  15200.  170

I want to create a matrix like df such that the output looks like

Strike. 15000.  15100.  15200.
15000.   0.      50.     120
15100.  -50      0.      20
15200.  -170.    -20.    0 

Its essentially looking to compute the difference in prices at all strikevalues.
Can you help how i can achieve this efficiently please.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think i need to use aggfunc, but somehow not getting the desired result

>Solution :

You can’t use pivot_table directly, you should use broadcasting:

a = df['Price'].to_numpy()
out = pd.DataFrame(a-a[:, None], columns=df['Strike2'], index=df['Strike.'])

Output:

Strike2  15000.0  15100.0  15200.0
Strike.                           
15000.0        0       50       70
15100.0      -50        0       20
15200.0      -70      -20        0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading