首页 > 解决方案 > 如何将打印语句的输出转换为python中的数据框?

问题描述

我无法将以下代码的输出转换为它自己的单独数据帧。我尝试创建一个列表并将其附加到一个列表中,但我收到一条错误消息,指出 df.append() 只能有一个输入。

import pandas as pd
import numpy as np
import yfinance as yf
import datetime as dt
from matplotlib import pyplot as plt
end = dt.datetime.now()
start = dt.date(end.year-20, end.month, end.day)
ticker= yf.Ticker('SPY')
df = ticker.history(interval = "1d", start = start, end = end)
df['TimeDate'] = df.index
df = df[['TimeDate','Close']]
retracement = 0.95
retracements = 0
retracementdays = 0
currenthigh = 0
retracementdays = 0
currenthigh = 0
for index,row in df.iterrows():
     if row['Close'] >= currenthigh:
        currenthigh = row['Close']
        retracementdays = 0
        print("All Time Highs",retracementdays)
     elif retracement*currenthigh <= row['Close'] <= currenthigh and retracementdays == 0: 
        print(row['TimeDate'],"Between All Time Highs and Retracement",retracementdays)
     elif row['Close'] <= retracement*currenthigh and retracementdays == 0: 
        retracementdays = retracementdays + 1
        retracements = retracements + 1
        print(row['TimeDate'], "Retracements",retracementdays)
    elif row['Close'] <= currenthigh and retracementdays != 0: # Under a retracement
        retracementdays = retracementdays + 1
        print(row['TimeDate'],"Under a Retracement to All Time Highs",retracementdays)

有人可以帮我把这段代码的输出变成它自己的数据框吗?

标签: pythonpandasdataframe

解决方案


是的,我不确定 df.append 是否会起作用,因为我正在传递多个值。我的打印语句有 3 个值。


推荐阅读