TypeError:' DataFrame'保存到csv时,对象不可调用

时间:2017-09-26 07:47:48

标签: python pandas csv pickle

我想将数据帧(从互联网下载,拾取然后取消下载)保存到本地csv文件,但始终在访问时遇到错误。见附件。

see my code as image

2 个答案:

答案 0 :(得分:2)

您无需尝试使用csv库手动编写CSV文件,因为您已经拥有Pandas Dataframe格式的saved。要将其保存为CSV,只需添加:

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

例如:

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() 

另请注意,使用format()可以简化字符串格式设置。

这会给你一个CSV输出文件,如下所示:

Excel screenshot

如果您仍想手动执行此操作:

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)

答案 1 :(得分:0)

错误显然在代码行中:

for row in saved():

保存后的括号会导致问题,因为它不是可调用的对象。

但是,您应该查看有关如何在StackOverflow上提问的指南,以便您提供正确的信息。