@@ -494,15 +494,12 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to
494
494
495
495
S = pd.Series([i / 100.0 for i in range (1 , 11 )])
496
496
497
-
498
497
def cum_ret (x , y ):
499
498
return x * (1 + y)
500
499
501
-
502
500
def red (x ):
503
501
return functools.reduce(cum_ret, x, 1.0 )
504
502
505
-
506
503
S.expanding().apply(red, raw = True )
507
504
508
505
@@ -514,12 +511,10 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to
514
511
df = pd.DataFrame({" A" : [1 , 1 , 2 , 2 ], " B" : [1 , - 1 , 1 , 2 ]})
515
512
gb = df.groupby(" A" )
516
513
517
-
518
514
def replace (g ):
519
515
mask = g < 0
520
516
return g.where(mask, g[~ mask].mean())
521
517
522
-
523
518
gb.transform(replace)
524
519
525
520
`Sort groups by aggregated data
@@ -551,13 +546,11 @@ Unlike agg, apply's callable is passed a sub-DataFrame which gives you access to
551
546
rng = pd.date_range(start = " 2014-10-07" , periods = 10 , freq = " 2min" )
552
547
ts = pd.Series(data = list (range (10 )), index = rng)
553
548
554
-
555
549
def MyCust (x ):
556
550
if len (x) > 2 :
557
551
return x[1 ] * 1.234
558
552
return pd.NaT
559
553
560
-
561
554
mhc = {" Mean" : np.mean, " Max" : np.max, " Custom" : MyCust}
562
555
ts.resample(" 5min" ).apply(mhc)
563
556
ts
@@ -803,11 +796,9 @@ Apply
803
796
index = [" I" , " II" , " III" ],
804
797
)
805
798
806
-
807
799
def SeriesFromSubList (aList ):
808
800
return pd.Series(aList)
809
801
810
-
811
802
df_orgz = pd.concat(
812
803
{ind: row.apply(SeriesFromSubList) for ind, row in df.iterrows()}
813
804
)
@@ -827,12 +818,10 @@ Rolling Apply to multiple columns where function calculates a Series before a Sc
827
818
)
828
819
df
829
820
830
-
831
821
def gm (df , const ):
832
822
v = ((((df[" A" ] + df[" B" ]) + 1 ).cumprod()) - 1 ) * const
833
823
return v.iloc[- 1 ]
834
824
835
-
836
825
s = pd.Series(
837
826
{
838
827
df.index[i]: gm(df.iloc[i: min (i + 51 , len (df) - 1 )], 5 )
@@ -859,11 +848,9 @@ Rolling Apply to multiple columns where function returns a Scalar (Volume Weight
859
848
)
860
849
df
861
850
862
-
863
851
def vwap (bars ):
864
852
return (bars.Close * bars.Volume).sum() / bars.Volume.sum()
865
853
866
-
867
854
window = 5
868
855
s = pd.concat(
869
856
[
0 commit comments