Alex
Alex

Reputation: 4995

Select columns based on a range and single integer using iloc()

Given the data frame below I want to select columns A and D to F.

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(5, 6)), columns=list('ABCDEF'))

In R I could say

df[ , c(1, 4:6)]

I want something similar for pandas. With

df.iloc[:, slice(3, 6, 1)]

I get columns D to F. But how can I add column A?

Upvotes: 1

Views: 1238

Answers (2)

Lepakk
Lepakk

Reputation: 449

Another option is np.split

df_split=pd.concat([np.split(df, [1],axis=1)[0],np.split(df,[3],axis=1)[1]],axis=1)

There you don't need to know the column names, just their positions.

Upvotes: 0

ALollz
ALollz

Reputation: 59519

You use np.r_ to pass combinations of slices and indices. Since you seem to know the labels, you could can use get_loc to obtain the iloc indices.

import numpy as np

idx = np.r_[df.columns.get_loc('A'), 
            df.columns.get_loc('D'):df.columns.get_loc('F')+1]
# idx = np.r_[0, 3:6]

df.iloc[:, idx]
    A   D   E   F
0  38  71  62  63
1  60  93  72  94
2  57  33  30  51
3  88  54  21  39
4   0  53  41  20

Upvotes: 2

Related Questions