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
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
...
🌐
Statology
statology.org › home › how to select multiple columns in pandas (with examples)
How to Select Multiple Columns in Pandas (With Examples)
September 14, 2021 - The following code shows how to select columns by name: #select columns called 'points' and 'blocks' df_new = df[['points', 'blocks']] #view new DataFrame df_new points blocks 0 25 4 1 12 7 2 15 7 3 14 6 4 19 5 5 23 8 6 25 9 7 29 10 · The following tutorials explain how to perform other common operations in pandas:
🌐
APXML
apxml.com › courses › essential-numpy-pandas › chapter-7-data-selection-indexing-pandas › selecting-columns
Select Columns Pandas DataFrame
Selected 'Name' column: 0 Alice ... labeled array, holding the data for that column along with its index. To select multiple columns, you again use square brackets []. However, inside the brackets, you provide a list of the column names you want to select:...
🌐
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 - You can use the following methods to select columns by name in a pandas DataFrame: Method 1: Select One Column by Name · df.loc[:, 'column1'] Method 2: Select Multiple Columns by Name · df.loc[:, ['column1', 'column3', 'column4']] Method 3: Select Columns in Range by Name ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-select-multiple-columns-in-a-pandas-dataframe
How to select multiple columns in a pandas dataframe - GeeksforGeeks
July 11, 2025 - It then selects and displays all rows while extracting columns 2 to 4 (Age, Address, and Qualification) using DataFrame slicing based on column indices ... # Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select all rows # and second to fourth column df[df.columns[1:4]]
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas select multiple columns in dataframe
Pandas Select Multiple Columns in DataFrame - Spark By {Examples}
June 10, 2025 - By using df[], loc[], iloc[], and get() you can select multiple columns from pandas DataFrame. When working with a table-like structure we are often
🌐
PythonHow
pythonhow.com › how › select-multiple-columns-in-a-pandas-dataframe
Here is how to select multiple columns in a Pandas dataframe in Python
Explanation In summary, to select multiple columns in a Pandas DataFrame, you can pass a list of column names or indices to the indexing operator '[]'. You can also use a slice to select a range of columns.
🌐
PythonForBeginners.com
pythonforbeginners.com › home › select multiple columns in a pandas dataframe
Select Multiple Columns in a Pandas Dataframe - PythonForBeginners.com
January 30, 2023 - If you want to select multiple columns in the pandas dataframe using the column names, you can use the loc attribute.
Find elsewhere
🌐
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.
🌐
GoLinuxCloud
golinuxcloud.com › home › databases › pandas › 5 ways to select multiple columns in a pandas dataframe
5 ways to select multiple columns in a pandas DataFrame | GoLinuxCloud
January 24, 2022 - # import the module import pandas ... we are going to select the columns using [] with dataframe column name. we have to use [[]] (double) to select multiple columns....
🌐
YouTube
youtube.com › watch
Select (Multiple) Columns in DataFrame | Pandas - YouTube
Different way on how to select columns in DataFramesSelection by name, slicing and boolean.Select first columns, last column, multiple columns
Published: March 10, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › pandas-select-columns
Pandas Select Columns - GeeksforGeeks
July 23, 2025 - Use bracket notation (df['column_name']) for selecting a single column. Use double square brackets (df[['column1', 'column2']]) for selecting multiple columns.
🌐
Sentry
sentry.io › sentry answers › python › select multiple columns in python pandas
Select multiple columns in Python Pandas | Sentry
March 15, 2023 - How do I select multiple columns from an existing DataFrame and create a new DataFrame with them? We can do this by creating a list of the column names we want and passing them to the DataFrame constructor method, along with the original DataFrame.
🌐
Squash
squash.io › how-to-select-multiple-columns-in-a-pandas-dataframe
How to Select Multiple Columns in a Pandas Dataframe
October 17, 2023 - In the above example, we used the loc[] method with the : operator to select all rows and the list ['Name', 'Age', 'Salary'] to select the desired columns. The resulting dataframe selected_columns contains only those selected columns.
🌐
Arab Psychology
scales.arabpsychology.com › home › how to easily select multiple columns in pandas dataframes
How To Easily Select Multiple Columns In Pandas DataFrames
December 4, 2025 - To select multiple columns by name, you pass a list of strings—where each string is the exact column header—directly inside the square brackets of the DataFrame. Note the use of double square brackets: the outer brackets denote the selection ...
🌐
Altcademy
altcademy.com › blog › how-to-select-multiple-columns-in-pandas
How to select multiple columns in Pandas - Altcademy.com
January 15, 2024 - Similarly, you can grab multiple columns from a DataFrame: columns_to_select = ['Name', 'City'] selected_columns = df[columns_to_select] The selected_columns DataFrame will now look like this: Name City 0 Alice New York 1 Bob Los Angeles 2 Charlie Chicago 3 David Houston · Pandas provides two powerful methods for selecting data: .loc and .iloc.
🌐
Ubiq BI
ubiq.co › home › how to select multiple columns in pandas dataframe
How to Select Multiple Columns in Pandas DataFrame - Ubiq BI
January 21, 2026 - In this case, you can select columns by simply supplying a list of column names. If you want to select many contiguous columns using their indexes, then you can use loc or iloc function.
🌐
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).