Skip to content Skip to sidebar Skip to footer

Python - Pandas - Write Dataframe To Csv

I'm trying to write a 4 table, 3 column, and 50 row dataframe file to a csv using pandas. I'm getting the following error AttributeError: 'dict' object has no attribute 'to_csv'. I

Solution 1:

Your intuition is right; there's nothing wrong with the syntax in your code.

You are receiving the AttributeError because you are reading data from multiple sheets within your workbook, generating a dictionary of DataFrames (instead of one DataFrame), from which you attempt to_csv (a method only available to a DataFrame).

As your code is written, the keys of the dictionary you generate correspond to the names of the worksheets, and the values are the respective DataFrames. It's all explained in the docs for the read_excel() method.

To write a csv file containing the aggregate data from all the worksheets, you could loop through the worksheets and append each DataFrame to your file (this works if your sheets have the same structure and dimensions):

import pandas as pd
import numpy as np

sheets = ['pnl1 Data ','pnl2 Data','pnl3 Data','pnl4 Data']

for sheet in sheets:
    df = pd.read_excel("filelocation.xlsx",
        sheetname=sheet,
        skiprows=8, 
        parse_cols="B:D", 
        keep_default_na='FALSE', 
        na_values=['NULL'])

    withopen('filelocation.csv', 'a') as f:
        df.to_csv(f, line_terminator=',', index=False, header=False)

Post a Comment for "Python - Pandas - Write Dataframe To Csv"