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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With