How to select range of columns in a dataframe based on their name and not their indexes?

前端 未结 5 1561
梦谈多话
梦谈多话 2020-12-21 09:50

In a pandas dataframe created like this:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(10, size=(6, 6)),
                  colu         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 10:21

    A solution using dplyr package but you need to specify the row you want to select before hand

    rowName2Match <- c("r1", "r5")
    
    df1 <- df %>% 
      select(matches("2"):matches("4")) %>% 
      add_rownames() %>% 
      mutate(idRow = match(rowname, rowName2Match)) %>% 
      slice(which(!is.na(idRow))) %>% 
      select(-idRow)
    df1
    
    > df1
    Source: local data frame [2 x 4]
    
      rowname    c2    c3    c4
          
    1      r1     2     3     4
    2      r5     6     7     8
    

提交回复
热议问题