I have a pandas dataframe which appears as:
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
I have a function defined as:
def Fn(S, G, SL):
#some complicated operation but for example it returns only product
return S*G*SL
I want to do the following for each row of df1 to get a dataframe as:
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)]
I tried the following:
z1 = df1.apply(map(lambda x:Fn([x, x.Grade, x.SleepNumber]), x.Sims))
But I am not setting it up correctly so it errors out.
You might rewrite your Fn as, since S is a column of lists:
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]
Or without modifying Fn , modify the map
function in the apply
method; Recall that map
by itself is not callable, you need to wrap it in another lambda :
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]
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.