【问题标题】:pandas load csv file ValueError熊猫加载csv文件ValueError
【发布时间】:2020-05-28 13:45:10
【问题描述】:

此脚本的目的是读取一个 csv 文件并创建一个 pandas 数据框,然后使用 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'>

【问题讨论】:

  • 已经在里面了

标签: python pandas oop


【解决方案1】:

罪魁祸首是__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(与 self.df 不同) Python)。你应该这样做:

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

【讨论】:

    猜你喜欢
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2018-09-22
    • 2018-12-02
    • 1970-01-01
    • 2022-11-19
    • 2018-05-28
    相关资源
    最近更新 更多