Taking into account this Pandas DataFrame df:
A B C D E F
0
1
2
With .loc method I can select specific columns like this:
df.loc[:, ['A','B','E']]
Or I can slice some columns like:
df.loc[:,'B':'E']
My question is? Can this method allow to combine these two options? For example for selecting the first column and slice other columns? I have tried:
df.loc[:,['A','D':'F']]
for selecting columns A, D, E, F.
Which is the correct syntax?
You cannot natively do this using labels with loc
, but you can do so using positions and np.r_
+ iloc
(it's the closest workaround).
f = df.columns.get_loc
df.iloc[:, np.r_[f('A'), f('D'):f('F')]]
A D E
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
This is under the assumption that your column names are unique.
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