ydopico ydopico - 6 days ago 6
Python Question

groupby apply not giving expected result

I am new to python, and I am trying to find the std of a circular data (wind directions) grouping the data by some characteristics.
Here is a set of the df I am using.

Profile bin inflow_direction
0 1 51 331.7
1 1 51 332.8
2 1 51 334.1
3 1 51 335.4
4 1 51 336.4
5 1 66 337.3
6 1 66 337.5
7 1 66 337.6
8 1 66 337.7
9 1 66 337.6


I need the std for every group of bin inside each Profile.
I have defined the std function as:

def circstd(j) :
samples = np.radians (j)
return scipy.stats.circstd(samples, high=6.283185307179586, low=0, axis=None)


when I group:

df.groupby(['Profile','bin']).apply(circstd)


The out is:

idscng_f bin
1 51 0.567811

66 0.671470


But I was expecting

idscng_f bin
1 51 0.0296

66 0.0025


What is the problem here?

Answer

Use np.std after converting angles from degrees to radians:

def simple_circstd(j) :
    return np.std(np.radians(j))['inflow_direction']

On applying df.groupby(['Profile','bin']).apply(simple_circtd):

Profile  bin
1        51     0.029650
         66     0.002367
dtype: float64
Comments