[英]How does one use doctest with a pandas dataframe?
我在一個名為test.py (見下文)的文件中有一個簡單的 function ( log_return
),我試圖用一個 doctest 來實現。
import pandas as pd
def log_return(df):
'''Return the log return based on closing prices
>>> df = pd.DataFrame({'Close': [100, 101, 102, 99]}, index = pd.date_range('2022-01-01', periods=4, freq='D'))
>>> log_return(df)
Close r
2022-01-01 100 NaN
2022-01-02 101 0.009950
2022-01-03 102 0.009852
2022-01-04 99 -0.029853
'''
df['r'] = np.log(df['Close']).diff()
但是,當我嘗試從命令行執行 doctest(例如$ python test.py
)時,出現以下與空格相關的錯誤。 我該如何解決這個錯誤?
ValueError: line 5 of the docstring for __main__.log_return has inconsistent leading whitespace: '2022-01-01 100 NaN'
你需要像這樣縮進它:
'''
...
>>> log_return(df)
Close r
2022-01-01 100 NaN
2022-01-02 101 0.009950
2022-01-03 102 0.009852
2022-01-04 99 -0.029853
'''
請記住,文檔測試看起來像交互式片段,因此在這種情況下,這意味着事物應該像在交互式 session(提示和輸出)中一樣對齊。
現在,一旦你解決了這個問題,測試就會失敗,但這是一個單獨的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.