python - pandas-how to apply different function to df.series while the function depending on another series? -
simply speaking, want this:
df.s1.map["a":df.s2+1, "b":df.s2-1] however,it won't work because df.s2 not constant.
how can map s1 on df.s2+1 while s1='a',and map s1 on df.s2-1 while s1='b'?
you can use apply using lambda axis = 1 i.e
if have dataframe
df = pd.dataframe({'s1':['a','b','a','a','b'],'s2':[1,3,5,2,4]}) df['s3'] = df.apply(lambda x : x['s2']+1 if x['s1'] == 'a' else x['s2']-1 ,axis=1 ) or take d['s2'] common dictionary , add @ end after mapping.
df['s3'] = df.s1.map({'a':1,'b':-1})+df['s2'] output:
s1 s2 s3 0 1 2 1 b 3 2 2 5 6 3 2 3 4 b 4 3 in [364]:
output :
wiki
Comments
Post a Comment