在2D数组中查找平均值

时间:2015-11-22 22:42:12

标签: python arrays numpy

我有2D numpy数组,代表x,y和z列'实际上它们是3D图像的点,你可以想象x作为索引重复,y是高度,z是我要找出的平均值,例如:

<WrapPanel Orientation="Horizontal">
                    <WrapPanel Orientation="Vertical">
                        <Label Name="SelectCOM" Content="{x:Static r:Translations.SelectCOM}" FontWeight="Bold" FontSize="12" />
                        <ComboBox Width="235" 
                                  x:Name="COMPorts" 
                                  SelectedItem="{Binding SelectedPort}" />
                    </WrapPanel>
                    <Button Margin="10,0,0,0" 
                            Width="70" 
                            Content="{x:Static r:Translations.Refresh}" 
                            HorizontalAlignment="Right" 
                            cal:Message.Attach="RefreshCOM" />
                </WrapPanel>

结果是这样的&#39;不是加号,而是结果是平均值&#39;:

public class MainViewModel : PropertyChangedBase
    {
        IDevice Device = null;
        private string selectedPort;

        public void RefreshCOM()
        {
            string[] ports = SerialPort.GetPortNames();


        }

        public string SelectedPort
        {
            get
            {
                return this.selectedPort;
            }

            set
            {
                this.selectedPort = value;
                this.NotifyOfPropertyChange(() => this.SelectedPort);
            }
        }
    }
如果我没有错,代码可能看起来像这样:

[[0, 1, 3],
 [0, 1, 4],
 [0, 2, 5],
 [0, 2, 6],
 [0, 3, 7],
 [1, 4, 0],
 [1, 4, 3],
 [1, 4, 1],
 [1, 2, 2],
 [1, 1, 2],
 [1, 5, 1]....]

1 个答案:

答案 0 :(得分:0)

这很天真,但我认为它可以做你想要的......

import itertools

# Make groups based on the first two elements. 
groups = itertools.groupby(a, key=lambda x: (x[0], x[1]))

# Iterate over the groups collecting the third elements.
result = []
for group in groups:
    this_set = []
    print(group)
    for i in group[1]:
        this_set.append(i[2])
    result.append([i[0], i[1], np.mean(this_set)])

results

的位置
[[0, 1, 3.5],
 [0, 2, 5.5],
 [0, 3, 7.0],
 [1, 4, 1.3333333333333333],
 [1, 2, 2.0],
 [1, 1, 2.0],
 [1, 5, 1.0]]