2017-04-24 73 views
1

我有作爲出現大熊貓數據幀:應用跨數據幀列函數爲每一行

df1['A'].ix[1:3]  Sims   Grade SleepNumber 
2017-01-01 02:00:00 [33, 34, 39] 5  6 
2017-01-01 03:00:00 [3, 43, 9] 1  12 

我有一個函數定義爲:

def Fn(S, G, SL): 
#some complicated operation but for example it returns only product 
return S*G*SL 

我想要做的每一行的以下的DF1得到一個數據幀爲:

df1['A'].ix[1:3]  FnResult 
2017-01-01 02:00:00 [Fn(33, 5, 6), Fn(34, 5, 6), Fn(39, 5, 6)] 
2017-01-01 03:00:00 [Fn(3, 1, 12), Fn(43, 1, 12), Fn(9, 1, 12)] 

我試過如下:

z1 = df1.apply(map(lambda x:Fn([x, x.Grade, x.SleepNumber]), x.Sims)) 

但我沒有正確設置它,所以它出錯了。

回答

0

你可能會重寫FN的,因爲小號是列表的列:

def Fn(S, G, SL): 
    return [s*G*SL for s in S] 

df['FnResult'] = df.apply(lambda r: Fn(r.Sims, r.Grade, r.SleepNumber), axis=1).values.tolist() 

df 
#       Sims Grade SleepNumber   FnResult 
#2017-01-01 02:00:00 [33, 34, 39] 5   6 [990, 1020, 1170] 
#2017-01-01 03:00:00  [3, 43, 9] 1   12  [36, 516, 108] 

或未經改動FN,請修改apply方法map功能;回想一下,map本身不是可調用的,你需要用它在另一個拉姆達

df['FnResult'] = df.apply(lambda r: list(map(lambda s: Fn(s, r.Grade, r.SleepNumber), r.Sims)), axis=1) 

df 
#        Sims Grade SleepNumber   FnResult 
#2017-01-01 02:00:00 [33, 34, 39]  5   6 [990, 1020, 1170] 
#2017-01-01 03:00:00 [3, 43, 9]   1   12  [36, 516, 108] 
+0

不幸的是FN的祖父,我不能重新寫。 – Zanam

相關問題