You can use Index.get_loc
or Index.searchsorted
for positions of columns:
Also is added max
function for avoiding error if select last column z
.
df = pd.DataFrame([range(26)], columns=L)
print (df)
a b c d e f g h i j ... q r s t u v w x y z
0 0 1 2 3 4 5 6 7 8 9 ... 16 17 18 19 20 21 22 23 24 25
print (df.columns[df.columns.get_loc('d'): max(df.columns.get_loc('v') + 1, len(df.index))])
Index(['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v'],
dtype='object')
Alternatively:
print (df.columns[df.columns.searchsorted('d'):
max(df.columns.searchsorted('v') + 1, len(df.index))])
Index(['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v'],
dtype='object')
Thank you Jon Clements for another solution:
print (df.columns.to_series()['d':'v'].values)
['d' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u'
'v']