使用for循环遍历DataFrame对象的列表

时间:2019-08-02 19:15:28

标签: python dataframe

我遇到此错误:

  

TypeError:列表索引必须是整数或切片,而不是DataFrame

divisasIndicaDataFrame对象的列表,我有以下代码:

datachart=[]
def dchart ():
    for i in divisasIndica[:]:
        df=divisasIndica[i]
        data = [ dict(
            type = 'candlestick',
            open = df.Open,
            high = df.High,
            low = df.Low,
            close = df.Close,
            x = df.index,
            rsi=df.RSI,
            SMA50=df.SMA50,
            SMA200=df.SMA200,
            SAR=df.SAR,
            yaxis = 'y2',
            name = tit,
            increasing = dict( line = dict( color = INCREASING_COLOR ) ),
            decreasing = dict( line = dict( color = DECREASING_COLOR ) ),
        ) ]
        layout=dict()

        fig = dict( data=data, layout=layout )
        datachart.append(fig)

问题是我不能用for读取DataFrame列表吗?

2 个答案:

答案 0 :(得分:0)

列表的值已经是数据帧,无需尝试使用索引获取它们。 for i in divisasIndica直接为您提供divisasIndica的所有元素,而不是它们的索引。无需执行divisasIndica[:]

将代码更改为此:

datachart=[]
def dchart ():
    for df in divisasIndica:
        data = [ dict(
            type = 'candlestick',
            open = df.Open,
            high = df.High,
            low = df.Low,
            close = df.Close,
            x = df.index,
            rsi=df.RSI,
            SMA50=df.SMA50,
            SMA200=df.SMA200,
            SAR=df.SAR,
            yaxis = 'y2',
            name = tit,
            increasing = dict( line = dict( color = INCREASING_COLOR ) ),
            decreasing = dict( line = dict( color = DECREASING_COLOR ) ),
        ) ]
        layout=dict()

        fig = dict( data=data, layout=layout )
        datachart.append(fig)

答案 1 :(得分:0)

datachart=[]
def dchart (divisasIndica):
    for df in divisasIndica:
        data = [ dict(
            type = 'candlestick',
            open = df.Open,
            high = df.High,
            low = df.Low,
            close = df.Close,
            x = df.index,
            rsi=df.RSI,
            SMA50=df.SMA50,
            SMA200=df.SMA200,
            SAR=df.SAR,
            yaxis = 'y2',
            name = titu,
            increasing = dict( line = dict( color = INCREASING_COLOR ) ),
            decreasing = dict( line = dict( color = DECREASING_COLOR ) ),

        ) ]
        layout=dict()

        fig = dict( data=data, layout=layout )
        datachart.append(fig)