Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Select Separate Columns [duplicate]

Given the following dataframe:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[1,2,3],'d':[4,5,6]})

df
   a  b  c  d
0  1  4  1  4
1  2  5  2  5
2  3  6  3  6

I want to select just columns a, c, and d by their column index positions. I tried the following with no luck:

df[df.columns[0],df.columns[-2:]]

I can probably figure it out via regular Python, but was wondering if there's a shortcut in pandas.

like image 907
Dance Party2 Avatar asked Jun 04 '26 18:06

Dance Party2


1 Answers

Using index append

df.loc[:,df.columns[[0]].append(df.columns[-2:])]
Out[1363]: 
   a  c  d
0  1  1  4
1  2  2  5
2  3  3  6

Or maybe just using .iloc

df.iloc[:,[0,2,3]] 

Ummm maybe np.r_

df.iloc[:,np.r_[0,-2:0]]
Out[1371]: 
   a  c  d
0  1  1  4
1  2  2  5
2  3  3  6
like image 63
BENY Avatar answered Jun 07 '26 07:06

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!