Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas combining slices and list to select columns

Tags:

python

pandas

Let us assume that a DataFrame df has the following columns: ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7']

We can use a slice or a list to select some columns:

  • With a slice: df.loc[:, 'c1':'c4']
  • With a list: df.loc[:, ['c1','c4','c6']]

If we want select ['c1', 'c4', 'c5', 'c6', 'c7']

It is not possible to do something like: ['c1', 'c4':'c7']. But you see the idea, is it possible to combine a list and a slice ?

like image 931
John Smith Avatar asked Oct 30 '25 20:10

John Smith


2 Answers

You can using np.r_ with the column header index like this:

df = pd.DataFrame(np.arange(49).reshape(7,-1), columns=[f'c{i}' for i in range(1,8)])
df.loc[:, df.columns[np.r_[0,3:7]]]

Output:

   c1  c4  c5  c6  c7
0   0   3   4   5   6
1   7  10  11  12  13
2  14  17  18  19  20
3  21  24  25  26  27
4  28  31  32  33  34
5  35  38  39  40  41
6  42  45  46  47  48
like image 91
Scott Boston Avatar answered Nov 01 '25 09:11

Scott Boston


Using directly the columnnames one could do it in the following way:

df.loc[:, ['c1'] + ['c{}'.format(i) for i in range(3, 8)]]
like image 36
Ruthger Righart Avatar answered Nov 01 '25 11:11

Ruthger Righart