Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple columns and slice columns at the same time with .loc method

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?

like image 902
Laura Avatar asked Sep 06 '25 16:09

Laura


1 Answers

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.

like image 53
cs95 Avatar answered Sep 08 '25 18:09

cs95