在numpy中从3d数组中删除2d子阵列

时间:2016-11-15 13:45:22

标签: python arrays numpy

在numpy中我有一个3d数组,我会删除一些2d子阵列。想想这样:

r = range(27)
arr = np.reshape(r, (3,3,3))

del = [[0,1,2],[0,0,2]]
flatSeam = np.ravel_multi_index(del, arr.shape)
arr = np.delete(arr, flatSeam)

所以最后我希望有一个形状(3,2,3)的数组,而不包含原始数组中的元素00, 10, 22。我的问题是我没有使用ravel_multi_index,因为我的索引是2d,数组形状是3d,所以计算错误的索引(上面的代码也没有执行因为索引数组和形状有是相同的大小)。

你有什么想法我能做到这一点吗?

1 个答案:

答案 0 :(得分:2)

这是一种使用advanced-indexing -

的方法
import {Component, OnInit} from '@angular/core';

import 'bootstrap/dist/css/bootstrap.css';
import '../css/main.css';

import {ChipFamilyService} from './chip-family/chip-family.service';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

import { TypeaheadMatch } from '../../node_modules/ng2-bootstrap/components/typeahead/typeahead-match.class';

import { IChipFamily } from './chip-family/chip-family';

@Component({
    selector: 'my-app',
    template: require('./app.component.html'),
    providers: [ChipFamilyService]
})

export class AppComponent implements OnInit {
    public typeaheadLoading:boolean = false;
    public typeaheadNoResults:boolean = false;
    public dataSource:Observable<any>;
    public asyncSelected:string = '';
    public selected: string = '';
    chipFamilies: Array<IChipFamily>;
    errorMessage: string;

    public constructor(private _adminService: ChipFamilyService) {
        this.dataSource = Observable.create((observer:any) => {
            // Runs on every search
            observer.next(this.asyncSelected);
        }).mergeMap((token:string) => this.getChipFamiliesAsObservable(token));
    }

    ngOnInit() {
        this._adminService.getChipFamilies().subscribe(
            chipFamilies => this.chipFamilies = chipFamilies,
            error => this.errorMessage = <any>error
        );
        console.log('AppComponent initializing...');
    }

    public getChipFamiliesAsObservable(token:string):Observable<any> {
        let query = new RegExp(token, 'ig');

        return Observable.of(
            this.chipFamilies.filter((chipFamily:any) => {
                return query.test(chipFamily.name);
            })
        );
    }
    public changeTypeaheadLoading(e:boolean):void {
        this.typeaheadLoading = e;
    }

    public changeTypeaheadNoResults(e:boolean):void {
        this.typeaheadNoResults = e;
    }

    public typeaheadOnSelect(e:TypeaheadMatch):void {
        console.log('Selected value: ', e.value);
    }
}

或者,使用boolean-indexing -

# arr: Input array, rm_idx : 2-row list/array of indices to be removed
m,n,p = arr.shape
mask = np.asarray(rm_idx[1])[:,None] != np.arange(n)
out = arr[np.arange(m)[:,None],np.where(mask)[1].reshape(m,-1)]

我们尽量避免创建out = arr.reshape(-1,p)[mask.ravel()].reshape(m,-1,p) 2D -

,因此内存密集度较低的方法
mask