1

Just curious, and quite new to Panda in Python,

   a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z
0  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2

Is there an effective way to select column a, b, then from j to t only, resulting in the output to be like this,

   a  b  j  k  l  m  n  o  p  q  r  s  t
0  1  1  1  1  1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  2  2  2  2  2  2

I can try,

original_column = original_dataframe[['a', 'b'...]]

But that will be too much of a hassle I rather use indexes but don't know how

Mr. T
  • 11,960
  • 10
  • 32
  • 54
John Ng
  • 35
  • 5

2 Answers2

2

Use:

df = df[['a','b'] + df.loc[:, 'j':'t'].columns.tolist()]
print (df)
   a  b  j  k  l  m  n  o  p  q  r  s  t
0  1  1  1  1  1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  2  2  2  2  2  2

Or:

df = pd.concat([df[['a','b']], df.loc[:, 'j':'t']], axis=1)
print (df)
   a  b  j  k  l  m  n  o  p  q  r  s  t
0  1  1  1  1  1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  2  2  2  2  2  2
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    mighty thanks, now I can effectively select multiple columns in different positions and ranges – John Ng Feb 18 '21 at 14:08
1

try to drop the columns

 df.drop(['B', 'C'], axis=1)

You will get the df just with the columns are remaining.

Geomario
  • 152
  • 1
  • 12