简体   繁体   中英

Function in function returning “TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' ”

I'm trying to get a moving avarage in a DataFrame (df).

The code that I have written is doing exactly what I want but this is just for 5 rows. see below:

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)

I would like to do the same for 200 rows and I don't think I need to copy past code "df.iloc[i +',i,', testcolumn] +" 200 times.

So created a function that helps me with the middle bit of the code. See below the code and the output:

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)

output:

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

This works, but how do I get these two combined?

I tried multiple options but it gives me contstantly the error:

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

The combined code looks as follows:

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)

I found an easier way to do the moving avarage: rolling avarage from pandas.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM