1

Raw columns look like this:

df.columns = ['a','b','c',...,'z']

there are 26 columns in a dataframe where starting 'a' element to 'z' one.

Output:

I want continuous columns where the start is 'd' and the end is 'v'.

new_cols = ['d','e',...,'v']

Trying:

df.loc[:,'d':'v'].columns

Hope:

I don't what the method about dataframe(like df.loc) but columns(like df.columns) which I could not find it.

Community
  • 1
  • 1
Jack
  • 1,724
  • 4
  • 18
  • 33
  • Are you after being able to slice the `df.columns` or getting your `df` with the rows but only those columns in it? – Jon Clements Aug 08 '17 at 15:01

2 Answers2

1

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']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

This answer was helpful.

If dfis your original a-z dataframe, do this:

import string
df[list(string.ascii_lowercase)[3:22]]

That will slice it the way you want it sliced.

cardamom
  • 6,873
  • 11
  • 48
  • 102