2017-10-10 106 views
2

目標:將N個int列表傳遞給函數,並將這些int用於1)。在熊貓數據框中創建並命名N列; 2)。使用這些整數作爲回溯期來計算滾動平均值。在for循環中創建並命名大熊貓系列

這裏是該函數的代碼(與重複性數據拉):收到

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) 

錯誤:

ValueError: Wrong number of items passed 2, placement implies 1

難道我在這裏有一個邏輯問題?我相信在for循環中它應該按順序傳遞整數,所以我不太明白它是如何一次傳遞多個值的。因此,我不確定如何解決問題。

根據這篇文章,當您同時將多個值傳遞給只能取一個值的容器時,會引發此錯誤。不應該for循環地址? ValueError: Wrong number of items passed - Meaning and suggestions?

回答

2

我認爲熊貓在分配從數據框應用的函數返回的值之前搜索列名稱。因此,分配系列初始化之前在開始時有些標柱從函數返回該列即

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