The column names (which are strings) cannot be sliced in the manner you tried.

Here you have a couple of options. If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the __getitem__ syntax (the []'s).

df1 = df[['a', 'b']]

Alternatively, if it matters to index them numerically and not by their name (say your code should automatically do this without knowing the names of the first two columns) then you can do this instead:

df1 = df.iloc[:, 0:2] # Remember that Python does not slice inclusive of the ending index.

Additionally, you should familiarize yourself with the idea of a view into a Pandas object vs. a copy of that object. The first of the above methods will return a new copy in memory of the desired sub-object (the desired slices).

Sometimes, however, there are indexing conventions in Pandas that don't do this and instead give you a new variable that just refers to the same chunk of memory as the sub-object or slice in the original object. This will happen with the second way of indexing, so you can modify it with the .copy() method to get a regular copy. When this happens, changing what you think is the sliced object can sometimes alter the original object. Always good to be on the look out for this.

df1 = df.iloc[0, 0:2].copy() # To avoid the case where changing df1 also changes df

To use iloc, you need to know the column positions (or indices). As the column positions may change, instead of hard-coding indices, you can use iloc along with get_loc function of columns method of dataframe object to obtain column indices.

{df.columns.get_loc(c): c for idx, c in enumerate(df.columns)}

Now you can use this dictionary to access columns through names and using iloc.

Answer from ely on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › getting_started › intro_tutorials › 03_subset_data.html
How do I select a subset of a DataFrame? — pandas 3.0.6 documentation
When using column names, row labels or a condition expression, use the loc operator in front of the selection brackets []. For both the part before and after the comma, you can use a single label, a list of labels, a slice of labels, a conditional expression or a colon.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas select columns by name or index
Pandas Select Columns by Name or Index - Spark By {Examples}
June 4, 2025 - In Pandas, selecting columns by name or index allows you to access specific columns in a DataFrame based on their labels (names) or positions (indices).
🌐
Statology
statology.org › home › how to select columns by name in pandas (3 examples)
How to Select Columns by Name in Pandas (3 Examples)
August 4, 2022 - #select column with name 'spurs' df.loc[:, 'spurs'] 0 10 1 12 2 14 3 13 4 13 5 19 6 22 Name: spurs, dtype: int64
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › pandas-select-columns
Pandas Select Columns - GeeksforGeeks
July 23, 2025 - If you want to select columns based on their data types (e.g., selecting only numeric columns), use the select_dtypes() method. ... Use bracket notation (df['column_name']) for selecting a single column.
Top answer
1 of 16
2742

The column names (which are strings) cannot be sliced in the manner you tried.

Here you have a couple of options. If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the __getitem__ syntax (the []'s).

df1 = df[['a', 'b']]

Alternatively, if it matters to index them numerically and not by their name (say your code should automatically do this without knowing the names of the first two columns) then you can do this instead:

df1 = df.iloc[:, 0:2] # Remember that Python does not slice inclusive of the ending index.

Additionally, you should familiarize yourself with the idea of a view into a Pandas object vs. a copy of that object. The first of the above methods will return a new copy in memory of the desired sub-object (the desired slices).

Sometimes, however, there are indexing conventions in Pandas that don't do this and instead give you a new variable that just refers to the same chunk of memory as the sub-object or slice in the original object. This will happen with the second way of indexing, so you can modify it with the .copy() method to get a regular copy. When this happens, changing what you think is the sliced object can sometimes alter the original object. Always good to be on the look out for this.

df1 = df.iloc[0, 0:2].copy() # To avoid the case where changing df1 also changes df

To use iloc, you need to know the column positions (or indices). As the column positions may change, instead of hard-coding indices, you can use iloc along with get_loc function of columns method of dataframe object to obtain column indices.

{df.columns.get_loc(c): c for idx, c in enumerate(df.columns)}

Now you can use this dictionary to access columns through names and using iloc.

2 of 16
297

As of version 0.11.0, columns can be sliced in the manner you tried using the .loc indexer:

df.loc[:, 'C':'E']

is equivalent to

df[['C', 'D', 'E']]  # or df.loc[:, ['C', 'D', 'E']]

and returns columns C through E.


A demo on a randomly generated DataFrame:

import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(100, 6)),
                  columns=list('ABCDEF'),
                  index=['R{}'.format(i) for i in range(100)])
df.head()

Out:
     A   B   C   D   E   F
R0  99  78  61  16  73   8
R1  62  27  30  80   7  76
R2  15  53  80  27  44  77
R3  75  65  47  30  84  86
R4  18   9  41  62   1  82

To get the columns from C to E (note that unlike integer slicing, E is included in the columns):

df.loc[:, 'C':'E']

Out:
      C   D   E
R0   61  16  73
R1   30  80   7
R2   80  27  44
R3   47  30  84
R4   41  62   1
R5    5  58   0
...

The same works for selecting rows based on labels. Get the rows R6 to R10 from those columns:

df.loc['R6':'R10', 'C':'E']

Out:
      C   D   E
R6   51  27  31
R7   83  19  18
R8   11  67  65
R9   78  27  29
R10   7  16  94

.loc also accepts a Boolean array so you can select the columns whose corresponding entry in the array is True. For example, df.columns.isin(list('BCD')) returns array([False, True, True, True, False, False], dtype=bool) - True if the column name is in the list ['B', 'C', 'D']; False, otherwise.

df.loc[:, df.columns.isin(list('BCD'))]

Out:
      B   C   D
R0   78  61  16
R1   27  30  80
R2   53  80  27
R3   65  47  30
R4    9  41  62
R5   78   5  58
...
🌐
GeeksforGeeks
geeksforgeeks.org › select-rows-columns-by-name-or-index-in-pandas-dataframe-using-loc-iloc
How to Select Rows & Columns by Name or Index in Pandas Dataframe - Using loc and iloc - GeeksforGeeks
November 28, 2024 - When working with labeled data or referencing specific positions in a DataFrame, selecting specific rows and columns from Pandas DataFrame is important. In this article, we’ll focus on pandas functions—loc and iloc—that allow you to select rows and columns either by their labels (names) or their integer positions (indexes).
🌐
Altcademy
altcademy.com › blog › how-to-select-specific-columns-in-pandas
How to select specific columns in Pandas - Altcademy.com
January 13, 2024 - You can think of .loc as using ... where you specify the numeric position in the DataFrame. The .loc method allows you to select columns by their names (labels)....
Top answer
1 of 2
42

You can remove one []:

df_new = df[list]

Also better is use other name as list, e.g. L:

df_new = df[L]

It look like working, I try only simplify it:

L = []
for x in df.columns: 
    if not "_" in x[-3:]: 
        L.append(x) 
print (L)

List comprehension:

print ([x for x in df.columns if not "_" in x[-3:]])
2 of 2
3

1. [] aka __getitem__()

The canonical way to select a list of columns from a dataframe is via [].

df = pd.DataFrame({'a': [1, 1, 1, 1], 'b': [2, 2, 1, 0], 'c': [3, 3, 1, 0]})
cols = ['a', 'b']

df1 = df[cols]

Note that all column labels in cols have to also be df (otherwise KeyError: "... not in index" will be raised).

One thing to note is that when you want to assign new columns to df1 as filtered above (e.g. df1['new'] = 0), a SettingWithCopyWarning will be raised. To silence it, explicitly make a new copy:

df1 = df[cols].copy()

2. Handle KeyError: "... not in index"

To ensure cols contains only column labels that are in df, you can call isin on the columns and then filter df.

cols = ['a', 'b', 'f']
df1 = df[cols]                           # <----- error
df1 = df.loc[:, df.columns.isin(cols)]   # <----- OK

3. filter()

Another way to select a list of columns from a dataframe is via filter(). A nice thing about it is that it creates a copy (so no SettingWithCopyWarning) and only selects the column labels in cols that exist in the dataframe, so handles the KeyError under the hood.

cols = ['a', 'b', 'f']
df1 = df.filter(cols)

As can be seen from the output below, f in cols is ignored because it doesn't exist as a column label in df.

Find elsewhere
🌐
Machine Learning Plus
machinelearningplus.com › blog › pandas select columns
Pandas Select Columns - machinelearningplus
March 8, 2022 - The parameter like of the .filter function defines this specific string. If a column name contains the string specified, that column will be selected and dataframe will be returned. ... Pandas dataframe has the function select_dtypes, which has an include parameter.
🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
pandas: Select rows/columns by index (numbers and names) | note.nkmk.me
August 8, 2023 - print(df[['col_2']]) print(type(df[['col_2']])) # col_2 # row_0 02 # row_1 12 # row_2 22 # row_3 32 # row_4 42 # <class 'pandas.core.frame.DataFrame'> ... You can also use loc to specify a slice based on column names, and iloc to select columns ...
🌐
KDnuggets
kdnuggets.com › 2019 › 06 › select-rows-columns-pandas.html
How to Select Rows and Columns in Pandas Using [ ], .loc, iloc, .at and .iat - KDnuggets
I organize the names of my columns into three list variables, and concatenate all these variables to get the final column order. I use the Set module to check if new_cols contains all the columns from the original. Then, I pass the new_cols variable to the indexing operator and store the resulting DataFrame in a variable "wine_df_2" . Now, the wine_df_2 DataFrame has the columns in the order that I wanted. Now, let's see how to use .iloc and loc for selecting rows from our DataFrame.
🌐
APXML
apxml.com › courses › essential-numpy-pandas › chapter-7-data-selection-indexing-pandas › selecting-columns
Select Columns Pandas DataFrame
Avoids Conflicts: A column name might clash with an existing DataFrame method or attribute (e.g., if you had a column named count, df.count would refer to the method, not your column). Bracket notation (df['count']) avoids this ambiguity. Consistency: Bracket notation is used for both single and multiple column selection (by passing a string vs.
🌐
Altcademy
altcademy.com › blog › how-to-select-columns-in-pandas
How to select columns in Pandas - Altcademy.com
January 10, 2024 - Pandas also provides methods like .filter() which can be used to select columns based on specific criteria, such as regular expressions or like patterns. This is like using a search function to quickly find all items on a menu that contain a particular ingredient. # Using .filter() to select columns containing 'Name' in their column name filtered_columns = df.filter(like='Name') print(filtered_columns)
🌐
Stack Abuse
stackabuse.com › bytes › how-to-select-columns-in-pandas-based-on-a-string-prefix
How to Select Columns in Pandas Based on a String Prefix
August 16, 2023 - The filter() function in pandas DataFrame provides a flexible and efficient way to select columns based on their names.
🌐
Pandas
pandas.pydata.org › docs › user_guide › indexing.html
Indexing and selecting data — pandas 3.0.6 documentation
When applied to a DataFrame, you can use a column of the DataFrame as sampling weights (provided you are sampling rows and not columns) by simply passing the name of the column as a string.
🌐
DataCamp
datacamp.com › tutorial › python-select-columns
Python Pandas Select Columns Tutorial | DataCamp
November 25, 2024 - Use Python Pandas and select columns from DataFrames. Follow our tutorial with code examples and learn different ways to select your data today!
🌐
Towards Data Science
towardsdatascience.com › home › latest › interesting ways to select pandas dataframe columns
Interesting Ways to Select Pandas DataFrame Columns | Towards Data Science
January 21, 2025 - By matching on columns that are the same data type, you'll get a series of True/False. Use the values method to get just the True/False values and not the index. ... If you have tons of columns in a data frame and their column names all have a similar substring that you are interested in, you can return the columns who's names contain a substring.
🌐
Seaborn
deeplearningnerds.com › pandas-select-columns-from-a-dataframe
Pandas - Select Columns from a DataFrame
December 2, 2023 - To do this, we use square brackets [] with a list of column names: new_df = df[["framework", "users"]] new_df · Another way is to use the loc() method of Pandas: new_df = df.loc[:, ["framework", "users"]] new_df · We can also select the columns ...
🌐
Programiz
programiz.com › python-programming › pandas › select
Pandas Select (With Examples)
import pandas as pd data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'], 'Age': [25, 30, 22, 27, 29], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'San Francisco'] } df = pd.DataFrame(data) print(f"Original DataFrame \n {df} \n") # loc to select rows and columns by labels # select rows 1 to 3 and columns Name and Age selected_data_loc = df.loc[1:3, ['Name', 'Age']] print(selected_data_loc.to_string(index = False)) print()