Reputation: 1237
Goal: pass a list of N ints to a function and use those ints to 1). create and name N columns in a pandas dataframe and; 2). calculate the rolling mean using those ints as lookback period.
here is the code for the function (with a data pull for reproducibility):
import pandas as pd
import pandas_datareader as web
test_df = web.DataReader('GDP', data_source = 'fred')
def sma(df, sma_lookbacks = [1,2]):
import pandas as pd
df = pd.DataFrame(df)
df = df.dropna()
for lookback in sma_lookbacks:
df[str('SMA' + str(lookback))] = df.rolling(window = lookback).mean()
return df.tail()
sma(test_df)
Error received:
ValueError: Wrong number of items passed 2, placement implies 1
Do I have a logic problem here? I believe in the for loop it should be passing the ints in sequence not at once, so I do not quite understand how it is passing more than one value at a time. As a result, I'm not sure how to troubleshoot.
According to this post, this error is thrown when you are simultaneously passing multiple values to a container that can only take one value. Shouldn't the for loop address that? ValueError: Wrong number of items passed - Meaning and suggestions?
Upvotes: 2
Views: 3790
Reputation: 30605
I think pandas search for column name before assigning the values returned from function applied on the dataframe. So initialize the column with some scalar in the begining before assigning series returned from a function to that column i.e
import pandas as pd
import pandas_datareader as web
test_df = web.DataReader('GDP', data_source = 'fred')
def sma(df, sma_lookbacks = [1,2]):
df = pd.DataFrame(df)
df = df.dropna()
for lookback in sma_lookbacks:
df[str('SMA' + str(lookback))] = 0
df[str('SMA' + str(lookback))] = df.rolling(window = lookback).mean()
return df.tail()
GDP SMA1 SMA2 DATE 2016-04-01 18538.0 18538.0 18431.60 2016-07-01 18729.1 18729.1 18633.55 2016-10-01 18905.5 18905.5 18817.30 2017-01-01 19057.7 19057.7 18981.60 2017-04-01 19250.0 19250.0 19153.85
Upvotes: 2