熊猫加载csv文件ValueError

时间:2020-05-28 13:45:10

标签: python pandas oop

此脚本的目的是读取一个csv文件并创建一个熊猫数据框,然后使用OOP样式打印前5个原始字符。

代码如下:

import pandas as pd
import talib


class Data:
    def __init__(self):
        self.df = pd.DataFrame()
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.file(self)

    def file(self, file):
        df = pd.read_csv(file, names=self.names,
                         parse_dates={'Release Date': ['Date', 'Time']})
        print(df.head())


x = Data()
x.file(file=r"D:\Projects\Project Forex\EURUSD.csv")

这是错误:

Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 15, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 9, in __init__
    self.file(self)

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 13, in file
    parse_dates={'Release Date': ['Date', 'Time']})

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\parsers.py", line 431, in _read
    filepath_or_buffer, encoding, compression

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\common.py", line 200, in get_filepath_or_buffer

    raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class '__main__.Data'>

1 个答案:

答案 0 :(得分:2)

罪魁祸首是__init__self.file(self)的最后一行。在__init__中调用selfData对象,而file方法必须使用包含csv文件路径的字符串来调用。

修复很简单:删除该行:

class Data:
    def __init__(self):
        self.df = pd.DataFrame()
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']

    def file(self, file):
        ...

,但仍然不一致:self.df初始化为空数据帧,这很好,但是file方法不会更新它,而是使用局部变量df(与Python中的self.df不同)。您应该这样做:

def file(self, file):
    self.df = pd.read_csv(file, names=self.names,
                     parse_dates={'Release Date': ['Date', 'Time']})
    print(self.df.head())