函数中的函数返回“ TypeError:+不支持的操作数类型:'int'和'NoneType'”

问题描述 投票:0回答:1

我正在尝试在DataFrame(df)中获取移动平均值。

我编写的代码完全可以实现我想要的功能,但这仅适用于5行。见下文:

def movingavarage (df,column, avg,remark):
    for i in range(0, df.shape[0] - avg):
        df.loc[df.index[i + avg],'SMA_5'] = np.round(((
        df.iloc[i + 0, column] +
        df.iloc[i + 1, column] +
        df.iloc[i + 2, column] +
        df.iloc[i + 3, column] +
        df.iloc[i + avg - 1, column]) /
        avg),1)

    return output(df, remark)

我想对200行进行同样的操作,我不认为我需要复制过去的代码“ df.iloc [i +',i,',testcolumn] +” 200次。

因此创建了一个函数,可帮助我使用代码的中间部分。参见下面的代码和输出:

input:

def loc (max):
    for i in range (0, max, 1):
        if i != max - 1:
            x = print ('df.iloc[i +',i,', testcolumn] +')
        elif i == max - 1:
            x = print ('df.iloc[i +',i,', testcolumn] ')
    return x

loc (4)

输出:

df.iloc[i + 0 , testcolumn] +
df.iloc[i + 1 , testcolumn] +
df.iloc[i + 2 , testcolumn] +
df.iloc[i + 3 , testcolumn] 

这有效,但是如何将这两个结合?

我尝试了多个选项,但不断给我错误:

File "/functions.py", line 45, in movingavarage2
    loc (4) +
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

合并后的代码如下:

def movingavarage2 (df,column, avg,remark):
    for i in range(0, df.shape[0] - avg):
        df.loc[df.index[i + avg],'SMA_5'] = np.round(((
        loc (4) +
        df.iloc[i + 4, column])/avg),1)

    return output(df, remark)
python function int range nonetype
1个回答
0
投票

[我发现了一种更简单的方法来进行移动平均:从熊猫滚动平均。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.rolling.Rolling.mean.html

© www.soinside.com 2019 - 2024. All rights reserved.