Python Pandas:与apply()一起使用时函数不起作用

时间:2017-01-03 23:22:54

标签: python pandas

以下功能:

def func(x):
    for k in x['slices']:
        for j in k:
            print(x['low'].iloc[j]) 

以下列方式应用:

func(test)

但如下所示:

test.apply(func, axis=1)

你能确定原因吗?

编辑:我仅将打印用于调试目的: 过去的功能是:

def func(x):
    result=[]
    for k in x:
        for j in k:    
            result.append(x['low'].iloc[j])
    return result

也没有用

在重构数据的元素下方。

df = pd.DataFrame(dict, columns=["low", "slices"])

   dict = {'low': {0: 1207.25,
      1: 1207.5,
      2: 1205.75,
      3: 1206.0,
      4: 1201.0,
      5: 1202.75,
      6: 1203.75},
     'slices': {0: [slice(1, 2, None)],
      1: [slice(1, 3, None), slice(2, 3, None)],
      2: [slice(1, 4, None), slice(2, 4, None), slice(3, 4, None)],
      3: [slice(1, 5, None),
       slice(2, 5, None),
       slice(3, 5, None),
       slice(4, 5, None)],
      4: [slice(1, 6, None),
       slice(2, 6, None),
       slice(3, 6, None),
       slice(4, 6, None),
       slice(5, 6, None)],
      5: [slice(1, 7, None),
       slice(2, 7, None),
       slice(3, 7, None),
       slice(4, 7, None),
       slice(5, 7, None),
       slice(6, 7, None)],
      6: [slice(1, 8, None),
       slice(2, 8, None),
       slice(3, 8, None),
       slice(4, 8, None),
       slice(5, 8, None),
       slice(6, 8, None),
       slice(7, 8, None)]}}

1 个答案:

答案 0 :(得分:2)

以这种方式定义你的功能

parse_type = "SVMLight"

并应用切片列

def fun(slices):
    return [df.low.loc[s].tolist() for s in slices]

enter image description here