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

Re-ordering and sorting of Pandas DataFrame – Python

I am trying to store values to the pandas dataframe and I am able to achieve that, but the problem is the data is being displayed horizontally. I want the data to be displayed vertically. You can see how the data is being currently displayed below.

enter image description here

I would also want the column names to be "cummulativeCall" instead of "unnamed 0" and "cummulativePut" instead of "unnamed 1" and "totalValue" instead of "unnamed 2". I also would have the dataframe sorted based on "totalValue"

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

The output I am expecting is

enter image description here

You can find the code below


      cum_call = []
      cum_put = []
      total_value = []
      strike_price = ce_data['strikePrice']
      cum_call = abs(closest_strike -  ce_data['strikePrice']) * (ce_data['openInterest'] * 50)
      cum_put = abs(closest_strike - pe_data['strikePrice']) * (pe_data['openInterest'] * 50)

      total_value = cum_call + cum_put

            #mp_result = pd.DataFrame([strike_price,cum_call, ce_data['askPrice'], cum_put, pe_data['askPrice'],total_value])
            mp_result = pd.DataFrame([strike_price, cum_call,  cum_put,  total_value])
)
print(mp_result)

I so far managed to have the data loaded into the frame, but I am not able to sort them and have it displayed as per my liking

>Solution :

Your question is missing a reproducible input.

That said, given the provided code, you’re creating 4 lists and combine them directly with the DataFrame constructor, which gives this unwanted wide format.

Instead, use a dictionary in the DataFrame constructor to create columns and sort_values:

mp_result = pd.DataFrame({
    'strike_price': strike_price,
    'cummulativeCall': cum_call,
    'cummulativePut': cum_put,
    'totalValue': total_value,
]).sort_values(by='totalValue')
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