iT邦幫忙

1

python 選擇讀取指定檔案,內容出現錯誤

選擇讀取指定檔案,再將train["Date"]時間進行轉換發生錯誤。
詢問要如何改善

Traceback (most recent call last):
  File "<ipython-input-81-7138c031ea33>", line 1, in <module>
    runfile('C:/Users/feather/Desktop/python20180626/test/load_data.py', wdir='C:/Users/feather/Desktop/python20180626/test')

  File "D:\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)

  File "D:\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/feather/Desktop/python20180626/test/load_data.py", line 55, in <module>
    train["Date"] = pd.to_datetime(train["Date"])

TypeError: 'NoneType' object is not subscriptable

程式碼

import pandas as pd

def load_data(v):
    class switch(object):
        def __init__(self, value):
            self.value = value
            self.fall = False

        def __iter__(self):
            """Return the match method once, then stop"""
            yield self.match
            raise StopIteration

        def match(self, *args):
            """Indicate whether or not to enter a case suite"""
            if self.fall or not args:
                return True
            elif self.value in args: # changed for v1.5, see below
                self.fall = True
                return True
            else:
                return False

    v = '1'
    for case in switch(v):
        if case('1'):
            pd.read_csv("SPY.csv", encoding='utf-8')
            print("Read SPY.csv OK")
            break
        if case('2'):
            pd.read_csv("SPY2.csv", encoding='utf-8')
            print("Read SPY2.csv OK")
            break
        if case(): # default, could also just omit condition or 'if True'
            print("something else!")


if __name__ == "__main__":
    train = load_data(1)
    
    train["Date"] = pd.to_datetime(train["Date"])
    train["year"] = train["Date"].dt.year
    train["month"] = train["Date"].dt.month
    train["date"] = train["Date"].dt.day
    train["day"] = train["Date"].dt.dayofweek
小魚 iT邦大師 1 級 ‧ 2019-07-21 17:17:44 檢舉
檔案內容是什麼?
檔案內容矩陣為6347*7
分為Date, Open, High, Low, Close, Adj Close, Volume
內容如下:
https://drive.google.com/file/d/1SGolkmQn50GjKsckT3C7TWqVjajvkDSd/view?usp=sharing
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
dragonH
iT邦超人 5 級 ‧ 2019-07-21 21:43:30
最佳解答

先說我 python 只有沾醬油的程度/images/emoticon/emoticon01.gif

你的問題應該是在於 switch 那沒有 return 東西

所以當你在 main 使用 train 時就會報錯

如果你是用 vscode 寫 python 的話

可以試著裝 python 的套件

我把你的 code 原封不動貼上

vscode 就丟出好幾個 error 要我改了

底下的 code 給你參考

可能不是寫得很好

請見諒

不過實測過是可以的

import pandas as pd
class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False
    def __iter__(self):
        yield self.match
        raise StopIteration
    def match(self, *args):
        if self.fall or not args:
            return True
        elif self.value in args:
            self.fall = True
            return True
        else:
            return False

def load_data(v = '1'):
    for case in switch(v):
        if case('1'):
            print("Read SPY.csv OK")
            return pd.read_csv("SPY.csv", encoding='utf-8')
            break
        elif case('2'):
            print("Read SPY2.csv OK")
            return pd.read_csv("SPY2.csv", encoding='utf-8')
            break
        else:
            print("something else!")

if __name__ == "__main__":
  train = load_data('1')
  train["Date"] = pd.to_datetime(train["Date"])
  train["year"] = train["Date"].dt.year
  train["month"] = train["Date"].dt.month
  train["date"] = train["Date"].dt.day
  train["day"] = train["Date"].dt.dayofweek
  print(train)

result

Read SPY.csv OK
           Date        Open        High         Low       Close   Adj Close     Volume  year  month  date  day
0    1993-01-29   43.968750   43.968750   43.750000   43.937500   26.706757    1003200  1993      1    29    4
1    1993-02-01   43.968750   44.250000   43.968750   44.250000   26.896694     480500  1993      2     1    0
2    1993-02-02   44.218750   44.375000   44.125000   44.343750   26.953669     201300  1993      2     2    1
3    1993-02-03   44.406250   44.843750   44.375000   44.812500   27.238594     529400  1993      2     3    2
4    1993-02-04   44.968750   45.093750   44.468750   45.000000   27.352570     531500  1993      2     4    3
...         ...         ...         ...         ...         ...         ...        ...   ...    ...   ...  ...
6341 2018-04-05  265.549988  266.640015  264.320007  265.640015  259.323303   82652600  2018      4     5    3
6342 2018-04-06  263.420013  265.109985  258.000000  259.720001  253.544052  179521200  2018      4     6    4
6343 2018-04-09  261.369995  264.839996  259.940002  261.000000  254.793640  105442900  2018      4     9    0
6344 2018-04-10  264.269989  266.040009  262.980011  265.149994  258.844940  103529000  2018      4    10    1
6345 2018-04-11  263.470001  265.640015  263.390015  263.760010  257.488007   91140200  2018      4    11    2

[6346 rows x 11 columns]

感謝你回答
我是用Anaconda3

我要發表回答

立即登入回答