Numpy删除3d数组中的列

时间:2018-01-27 15:52:48

标签: python arrays numpy multidimensional-array

我有一个3d Numpy数组,例如:

array = np.array([[[1,2],[3,4]],[[0,5],[6,7]]])
=[[[1 2]
   [3 4]]
  [[0 5]
   [6 7]]]

我想删除同一列中的元素,例如第1列。结果应该是:

=[[[1]
   [3]]
  [[0]
   [6]]]

我尝试了np.delete函数:

print np.delete(array[:][:],1,axis=1)

但它不能产生预期的结果,而是得到:

=[[[1 2]]
  [[0 5]]]

我在np doc (Link)中找到了这个:

np.delete(array, np.s_[::2], 1)

但这似乎只是删除了不均匀的数字,我不知道如何修改它。 np.s函数上的文档也没有让我更进一步。

任何帮助都将受到高度赞赏!

3 个答案:

答案 0 :(得分:2)

您的数组是三个维数组,因此如果您要删除最后一个索引的索引1的项目,您应该使用:

np.delete(array[:][:], 1, axis=2)

请注意,您需要[:][:]部分:这将无效,因此您可以使用:

np.delete(array, 1, axis=2)

然后会生成:

>>> np.delete(array, 1, axis=2)
array([[[1],
        [3]],

       [[0],
        [6]]])

答案 1 :(得分:2)

使用axis = [0,1]删除在使用2d数组时有效。随着尺寸的增加,轴的值也应相应增加。 这应该有用。

np.delete(array[:][:], 1, axis=2)

答案 2 :(得分:0)

您可以很好地使用基本切片,因为np.delete()实际上删除原始数组中的任何内容。相反,它会返回一份副本(您正在请求的内容)。

library(rgdal)
library(leaflet)

tmp <- tempdir()
url <- "http://personal.tcu.edu/kylewalker/data/mexico.zip"
file <- basename(url)
download.file(url, file)
unzip(file, exdir = tmp)
mexico <- readOGR(dsn = tmp, layer = "mexico", encoding = "UTF-8")

pal <- colorQuantile("YlGn", NULL, n = 5)
state_popup <- paste0("<strong>Estado: </strong>", 
                      mexico$name, 
                      "<br><strong>PIB per c?pita, miles de pesos, 2008: </strong>", 
                      mexico$gdp08)

# load necessary packages
library(leaflet)    
library(shiny)
library(shinydashboard)


ui <- fluidPage(
  # place the contents inside a box
  shinydashboard::box(
    width = 12
    , title = "Click on the map!"
    # separate the box by a column
    , column(
      width = 2
      , shiny::actionButton( inputId = "clearHighlight"
                             , icon = icon( name = "eraser")
                             , label = "Clear the Map"
                             , style = "color: #fff; background-color: #D75453; border-color: #C73232"
      )
    )
    # separate the box by a column
    , column(
      width = 10
      , leaflet::leafletOutput( outputId = "myMap"
                                , height = 850
      )
    )
  ) # end of the box
) # end of fluid page

# create the server
server <- function( input, output, session ){

  # function to create foundational map
  foundational.map <- function(){
    leaflet() %>%
      #addTiles( urlTemplate = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png") %>%
      #setView( lng = -87.567215
      #         , lat = 41.822582
      #         , zoom = 11 ) %>%
      addProviderTiles("CartoDB.Positron") %>%
      addPolygons( data = mexico
                   , fillOpacity = 0
                   , opacity = 0.2
                   , color = "#000000"
                   , weight = 2
                   , layerId = mexico$state
                   , group = "click.list")
  }

  # reactiveVal for the map object, and corresponding output object.
  myMap_reval <- reactiveVal(foundational.map())
  output$myMap <- renderLeaflet({
    myMap_reval()
  }) 

  # To hold the selected map region id.
  click.list <- shiny::reactiveValues( ids = vector() )

  shiny::observeEvent( input$myMap_shape_click, ignoreNULL = T,ignoreInit = T, {

    # If already selected, first remove previous selection
    if(length(click.list)>0)
    {
      remove_id = click.list$ids
      lines.of.interest <- mexico[ which( mexico$state %in% remove_id) , ]
      leaflet::leafletProxy( mapId = "myMap" ) %>%
        addPolylines( data = lines.of.interest
                      , layerId = lines.of.interest@data$id
                      , color = "#000000"
                      , weight = 2
                      , opacity = 0.2)
    }

    # add current selection
    click <- input$myMap_shape_click
    click.list$ids <- click$id  # we only store the last click now!
    lines.of.interest <- mexico[ which( mexico$state %in% click.list$ids ) , ]
    print(click)
    if( is.null( click$id ) ){
      req( click$id )
    } else if( !click$id %in% lines.of.interest@data$id ){
      leaflet::leafletProxy( mapId = "myMap" ) %>%
        addPolylines( data = lines.of.interest
                      , layerId = lines.of.interest@data$id
                      , color = "#6cb5bc"
                      , weight = 5
                      , opacity = 1
        ) 
    }

  }) # end of shiny::observeEvent({})

  # oberver for the clearHighlight button.
  shiny::observeEvent( input$clearHighlight, {
    click.list$ids <- NULL
    myMap_reval(foundational.map()) # reset map.
  }) 

} 

shiny::shinyApp( ui = ui, server = server)

但是,如前所述,np.delete() 会将结果作为副本返回

In [242]: arr
Out[242]: 
array([[[1, 2],
        [3, 4]],

       [[0, 5],
        [6, 7]]])

# select both slices, select all rows but only first column
In [243]: arr[:, :, :1]
Out[243]: 
array([[[1],
        [3]],

       [[0],
        [6]]])

# same case as above but you can omit the `:`s with a single `...`
In [244]: arr[..., :1]
Out[244]: 
array([[[1],
        [3]],

       [[0],
        [6]]])

# sanity check for no copy made
In [245]: (arr[..., :1]).flags
Out[245]: 
  C_CONTIGUOUS : False
  F_CONTIGUOUS : False
  OWNDATA : False   # <=========== NO copy
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

但是,如果您从原始数组进行切片,则在对结果进行任何更改时要小心,以免意外更改原始数组。