John Ng
John Ng

Reputation: 35

Selecting columns in Panda

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

Upvotes: 1

Views: 65

Answers (2)

Geomario
Geomario

Reputation: 212

try to drop the columns

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

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

Upvotes: 1

jezrael
jezrael

Reputation: 862376

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

Upvotes: 2

Related Questions