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:
df.loc[:, 'c1':'c4']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 ?
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
Using directly the columnnames one could do it in the following way:
df.loc[:, ['c1'] + ['c{}'.format(i) for i in range(3, 8)]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With