20

I have extracted xlsx data into pandas dataframe and used style.format to format particular columns into percentages and dollars. So now my dataframe is converted to styler object, because I need to parse this data into csv. I have to convert this object into dataframe please help.

below is the code and output:

import pandas as pd
import numpy as np

file_path = "./sample_data.xlsx"

df = pd.read_excel(file_path, sheet_name = "Channel",skiprows=10, header = 
[0,1,2])

dollar_cols = ['SalesTY', 'SalesLY','InStoreTY', 'InStoreLY','eCommTY']

dollar_dict = {}
for dollar_col in dollar_cols: 
    formatdict[dollar_col] = "${:,.0f}"
    final_df = df.style.format(formatdict)

Here final_df has the columns converted to dollars but I am unable to convert this to csv or into a data frame. It's a styler object now, I need to convert this into a data frame again. Any help is appreciated. Thanks.

1
  • good question, please share with us your codes and a bit of sample data. Commented Mar 20, 2019 at 10:46

1 Answer 1

17

You can retrieve the original dataframe from the styler object using the "data" attribute.

In your example:

df = final_df.data

type(df) yields

pandas.core.frame.DataFrame

Sign up to request clarification or add additional context in comments.

6 Comments

This method works but you lose the formatting in the process.
Yes. The question was to get the original data frame back. The formatting is of course in the styling object the questioner already has.
And how do I get a new dataframe with the correct new format?
you want a dataframe with formattng which is not a styler or using styles?if you actually want to see $ symbols in the exported csv you will need to replace the numbers with strings, e.g. replace 1000 with $1,000. are you sure that's what you want? why would you want that?
I would be fine with "losing the formatting" if the formatting was still stored in the new data frame's style attribute. style.data.style should be an identity. Alas, it is not.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.