python - pandas dataframe error when export style object to csv
Asked Answered
C

3

6

I have a dataframe that is formatted differently for each column. I need to export it to csv or dat files. But got the following error message:

AttributeError: 'Styler' object has no attribute 'to_csv'

How to solve this issue?

import pandas as pd
import datetime

def time_formatter(data):
    return datetime.datetime.strptime(data, "%Y/%m/%d").date().strftime('%Y%m%d')

df = pd.DataFrame({'a':[1,2,3], 'b':['2017/01/01', '2017/01/02','2016/12/31'], 'c':['aaa', 'bbb', 'ccc'], 'd':[4,5,6]})

formatter = {'a':'{:4.2f}', 'b': time_formatter, 'd':'{:8.2f}'}

df = df.style.format(formatter)

df.to_csv('aaa.csv')
Carolecarolee answered 27/6, 2017 at 20:32 Comment(8)
The code you've included runs without error. Can you please include the part of your code that is throwing the error? But the issue is almost certainly that you're calling to_csv on a Styler object instead of a DataFrame.Leeland
I've edited my post.Carolecarolee
What version of Python are you using? Can you post the full traceback? This again runs on my system without error (and outputs aaa.csv)Leeland
I forgot to add "df = df.style.format(formatter)". The reason why you had no error was the df has not been altered. Now the df is a Styler object, and when exporting to csv it will give us error. Can you try again?Carolecarolee
So, I believe the issue is that you're overwriting your data frame, as the style application should be inplace. However, I'm not sure pandas styles work with anything except the HTML representation.Leeland
@AlexAlifimoff you are right. That's the same thing that I got so far regarding pandas styler objects. Not sure if there is a way to solve this issue.Carolecarolee
@AlexAlifimoff It looks like the openpyxl engine can do the work: pandas.pydata.org/pandas-docs/stable/style.htmlCarolecarolee
The other option would be to just change the columns to strings (formatted as you desire) and then export to CSV.Leeland
L
5

Well, it is because CSV is a plain text format and these files don't contain styling (formatting) information. That's why you are getting AttributeError: 'Styler' object has no attribute 'to_csv'. You need to save it as an excel file to use different stylings.

Legra answered 16/5, 2019 at 7:6 Comment(0)
M
2

Not using to_csv, but what you want:

from pathlib import Path

s = df.style.hide(axis='index').format(formatter)

path = Path('aaa.csv')
path.write_text(','.join(df.columns))
path.write_text(s.to_string(delimiter=','))

Please 👍🏻 / comment here to get to_csv on styler.

Methenamine answered 6/6, 2023 at 5:4 Comment(0)
A
1

I also face same problem and it solved by flowing this
At first import

pip install openpyxl

then save your file as

df.to_excel("output.xlsx")
Ambassador answered 11/9, 2020 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.