对象中pandas group中n和n + 1行之间的平均值?

时间:2018-05-04 06:02:01

标签: python pandas pandas-groupby rolling-computation rolling-average

我有一个groupby对象:

<field name="myProjectList" 
       type="sql" 
       default="10" 
       label="Select an article"
       query="SELECT id, title FROM #__projectinfo"
       key_field="id" // Use your respected key_field column
       value_field="title" //Use your respected value_field column
    />

如何将groupby对象排序为以下内容:

  col1 col2         x         y         z
0    A   D1  0.269002  0.131740  0.401020
1    B   D1  0.201159  0.072912  0.775171
2    D   D1  0.745292  0.725807  0.106000
3    F   D1  0.270844  0.214708  0.935534
4    C   D1  0.997799  0.503333  0.250536
5    E   D1  0.851880  0.921189  0.085515

然后计算行A {x,y,z}和行B {x,y,z},行B {x,y,z}和行C {x,y,z}之间的均值。这样我有:

  col1 col2         x         y         z
0    A   D1  0.269002  0.131740  0.401020
1    B   D1  0.201159  0.072912  0.775171
4    C   D1  0.997799  0.503333  0.250536
2    D   D1  0.745292  0.725807  0.106000
5    E   D1  0.851880  0.921189  0.085515
3    F   D1  0.270844  0.214708  0.935534

我基本上试图在计算上找到六边形结构顶点之间的中点(好吧......更像是1000万)。提示赞赏!

1 个答案:

答案 0 :(得分:0)

我认为您需要groupby使用rolling并汇总mean,最后一对使用shift并删除每个组的第一个NaN行:

print (df)
 col1 col2         x         y         z
0    A   D1  0.269002  0.131740  0.401020
1    B   D1  0.201159  0.072912  0.775171
2    D   D1  0.745292  0.725807  0.106000
3    F   D2  0.270844  0.214708  0.935534 <-change D1 to D2
4    C   D2  0.997799  0.503333  0.250536 <-change D1 to D2
5    E   D2  0.851880  0.921189  0.085515 <-change D1 to D2
#
df = (df.sort_values(['col1','col2'])
        .set_index('col1')
        .groupby('col2')['x','y','z']
        .rolling(2)
        .mean()
        .reset_index())
df['col1'] = df.groupby('col2')['col1'].shift() + '-' + df['col1']
df = df.dropna(subset=['col1','x','y','z'], how='all')
#alternative
#df = df[df['col2'].duplicated()]
print (df)

  col2 col1         x         y         z
1   D1  A-B  0.235081  0.102326  0.588095
2   D1  B-D  0.473226  0.399359  0.440586
4   D2  C-E  0.924840  0.712261  0.168026
5   D2  E-F  0.561362  0.567948  0.510524
相关问题