Search code examples
pythonpandaspandas-loc

Slicing columns with .loc inconsistently


I have a dataframe like this

df = pd.DataFrame({'a': [1], 'b': [1], 'c': [1], 'd':[1], 'e':[1]})
df

I want to select a,b,c,e columns with .loc! I find

l=df.loc[:, 'a':'c'].columns.to_list()
l+=['e']
df.loc[:, l]

But is there more convinient way? like

df.loc[:, ['a':'c', 'e']]

In real dataframe number of columns is much more than in this dataframe.


Solution

  • Option 1:

    df2 = df.drop('d', axis=1)
    

    Option 2:

    df2 = df.iloc[:, np.r_[0:3, 4]]
    

    Option 3:

    df2 = df.filter(regex='[^d]')
    

    Option 4:

    df2 = df[list(df.loc[:,'a':'c']) + ['e']]