Fulviooo
Fulviooo

Reputation: 33

TypeError: 'DataFrame' object is not callable when saving to csv

I want to save a dataframe (downloaded data from internet, picked and then unpickled) to local csv file, but always getting errors on accessing it. See attached code.

see my code as image

Upvotes: -1

Views: 1898

Answers (2)

Stuart Buckingham
Stuart Buckingham

Reputation: 1784

The error is obviously in the line of code:

for row in saved():

The brackets after saved are causing an issue because it is not a callable object.

Upvotes: 0

Martin Evans
Martin Evans

Reputation: 46779

There is no need to try and manually write your CSV file using the csv library as you already have saved in a Pandas Dataframe format. To save this to CSV is a simple as just adding:

saved.to_csv('{}{}{}.csv'.format(share, date_fm, date_to))

For example:

import pickle
from yahoo_historical import Fetcher
import csv

def loadDownloader(share, date_fm, date_to):
    data = Fetcher(share, date_fm, date_to)
    return(data.getHistorical())

def saveDownloader(downloader, share, date_fm, date_to):
    with open('{}{}{}.pickle'.format(share, date_fm, date_to), 'wb') as f:
        pickle.dump(downloader, file=f, protocol=pickle.HIGHEST_PROTOCOL)

def main():
    downloader = None
    share = str(input('share, eg. "UCG.MI" : '))
    y_fm = int(input('start date Year : '))
    m_fm = int(input('start date Month : '))
    d_fm = int(input('start date Day : '))
    y_to = int(input('end date Year : '))
    m_to = int(input('end date Month : '))
    d_to = int(input('end date Day : '))

    date_fm = [y_fm, m_fm, d_fm]
    date_to = [y_to, m_to, d_to]
    print("Retrieving data")
    downloader = loadDownloader(share, date_fm, date_to)
    saveDownloader(downloader,share, date_fm, date_to)

    with open('{}{}{}.pickle'.format(share, date_fm, date_to), 'rb') as f:
        saved = pickle.load(f)

    print("Exporting in progress")
    saved.to_csv('{}{}{}.csv'.format(share, date_fm, date_to))
    print("Job done")

if __name__ == "__main__":
    main() 

Also note the use of format() to make your string formatting easier.

This would give you a CSV output file looking like:

Excel screenshot

If you still wanted to do it manually:

with open('{}{}{}.csv'.format(share, date_fm, date_to), 'w', newline='') as fileobj:
    newFile = csv.writer(fileobj)
    newFile.writerow(saved.columns.values)   # Get header names

    for index, row in saved.iterrows():
        newFile.writerow(row)

Upvotes: 2

Related Questions