panda groupby ID, and compute radius with respect to the center of the coordinates

Viewed 92

I have a panda dataframe df with the id, and the physical coordinates (x, y) of groups of particles. I want use panda dataframe with these steps: groupby with the id, compute the distance R=np.sqrt((x-x_c)**2+(y-y_c)**2) of each particle from its center. x_c and y_c (center coordinates) are computed from:

df2=df.groupby('id', as_index=False)['x','y'].mean()
df2.columns=['id', 'x_c', 'y_c']

From this dataframe:

          id       x         y        
0         33434.0  57580.40  65684.5  
1         33434.0  57580.10  65684.8  
2         33434.0  57580.20  65684.6  
3         33434.0  57580.40  65684.8  
          ...       ...      ...
817526  5621337.0  37264.00  53945.2  
817527  5621337.0  57161.90  65303.3 
817528  5621337.0  57287.80  65933.2  
817529  5621337.0  58111.30  66987.5  

I want to obtain this dataframe:

          id       x         y        R
0         33434.0  57580.40  65684.5  0.21505813
1         33434.0  57580.10  65684.8  0.21505813
2         33434.0  57580.20  65684.6  0.10606601
3         33434.0  57580.40  65684.8  0.17677669
          ...       ...      ...
817526  5621337.0  37264.00  53945.2  17707.67
817527  5621337.0  57161.90  65303.3  5220.65
817528  5621337.0  57287.80  65933.2  5630.37
817529  5621337.0  58111.30  66987.5  6895.2

Thanks!

1 Answers

We can group the dataframe by id and transform the columns x and y using mean then subtract the transformed mean from the columns x and y to center each particle, then use the distance formula to calculate the resulting column R

c = ['x', 'y']
df['R'] = ((df[c] - df.groupby('id')[c].transform('mean')) ** 2).sum(1) ** 0.5

               id        x        y             R
0         33434.0  57580.4  65684.5      0.215058
1         33434.0  57580.1  65684.8      0.215058
2         33434.0  57580.2  65684.6      0.106066
3         33434.0  57580.4  65684.8      0.176777
...
817527  5621337.0  57161.9  65303.3   5220.657327
817528  5621337.0  57287.8  65933.2   5630.379935
817529  5621337.0  58111.3  66987.5   6895.229767
Related