简体   繁体   中英

Pandas - Groupby or Cut multi dataframes to bins

I'm having a dataframe with starting axis points and their end points like this

x       y       x_end   y_end   distance
14.14   30.450  31.71   41.265  20.631750
-27.02  55.650  -33.60  63.000  9.865034
-19.25  70.665  -28.98  80.115  13.563753
16.45   59.115  9.94    41.895  18.409468

I'm drawing a heatmap. I need each "zone" of that map has a line which shows the average distance and angle of lines which have x/y from that zone and their x_end/y_end. It looks like this在此处输入图片说明

My bins is

xbins = np.linspace(-35, 35, 11)

ybins = np.linspace(0, 105, 22)

I've already plotted a heatmap

在此处输入图片说明

I'm looking for something like this

Bins_X           Bins_Y     Average_X_End   Average_Y_End   Average_Distance
(-35.0, -28.0]  (0, 5.0]    31.71           41.265          20.631750
(-28.0, -21.0]  (0, 5.0]    -33.60          63.000          9.865034
(-21.0, -14.0]  (0, 5.0]    -28.98          80.115          13.563753
(-14.0, -7.0]   (0, 5.0]    9.94            41.895          18.409468
(-35.0, -28.0]  (5.0, 10.0] 41.265          31.71           13.563753
(-28.0, -21.0]  (5.0, 10.0] 63.000          -33.60          18.409468
(-21.0, -14.0]  (5.0, 10.0] 80.115          -28.98          20.631750
(-14.0, -7.0]   (5.0, 10.0] 41.895          9.94            9.865034

Something like this?

(df.drop(['x','y'], axis=1)
  .groupby([pd.cut(df.x, xbins),
            pd.cut(df.y, ybins)],
          )
   .mean()
   .dropna(how='all')
   .add_prefix('Average_')
)

Output:

                             Average_x_end  Average_y_end  Average_distance
x              y                                                           
(-28.0, -21.0] (55.0, 60.0]         -33.60         63.000          9.865034
(-21.0, -14.0] (70.0, 75.0]         -28.98         80.115         13.563753
(14.0, 21.0]   (30.0, 35.0]          31.71         41.265         20.631750
               (55.0, 60.0]           9.94         41.895         18.409468

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM