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
...
🌐
Python Examples
pythonexamples.org › pandas-dataframe-select-multiple-columns-by-index
Pandas DataFrame - Select Multiple Columns by Index
To select multiple columns by index in DataFrame in Pandas, you can use iloc property of the DataFrame. DataFrame.iloc property lets us choose required columns based on index from the DataFrame.
People also ask

What is the method to select columns by their numerical index in Pandas
ANS: Use the .iloc accessor: df.iloc[:, [index1, index2]] for specific indices, or df.iloc[:, start_index:end_index] for a range of indices. Remember that Python indexing is zero-based and exclusive of the end index in slices.
🌐
sqlpey.com
sqlpey.com › python › pandas-select-multiple-columns
Pandas: Select Multiple Columns by Name or Index - sqlpey
How do I select multiple columns by name in a Pandas DataFrame
ANS: You can pass a list of column names to the DataFrame’s indexing operator: df[['column1', 'column2']]. Alternatively, use df.loc[:, ['column1', 'column2']] or df.filter(items=['column1', 'column2']).
🌐
sqlpey.com
sqlpey.com › python › pandas-select-multiple-columns
Pandas: Select Multiple Columns by Name or Index - sqlpey
How can I select columns by a range of names using Pandas
ANS: The .loc accessor is ideal for this: df.loc[:, 'start_column_name':'end_column_name']. Note that the end column name is inclusive in this slicing.
🌐
sqlpey.com
sqlpey.com › python › pandas-select-multiple-columns
Pandas: Select Multiple Columns by Name or Index - sqlpey
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › indexing-and-selecting-data-with-pandas
Indexing and Selecting Data with Pandas - GeeksforGeeks
The [] operator is the basic and frequently used method for indexing in Pandas. It allows us to select columns and filter rows based on conditions. This method can be used to select individual columns or multiple columns.
Published: April 28, 2026
🌐
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 - Notice that the columns in index positions 0, 1, and 3 are selected. Note: The first column in a pandas DataFrame is located in position 0.
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › user_guide › indexing.html
Indexing and selecting data — pandas 3.0.6 documentation
Trying to use a non-integer, even a valid label will raise an IndexError. The .iloc attribute is the primary access method. The following are valid inputs: An integer e.g. 5. A list or array of integers [4, 3, 0]. A slice object with ints 1:7. A boolean array. A callable, see Selection By Callable. A tuple of row (and column) indexes, whose elements are one of the above types.
🌐
Statology
statology.org › home › how to select columns by index in a pandas dataframe
How to Select Columns by Index in a Pandas DataFrame
March 27, 2025 - If you’d like to select columns based on label indexing, you can use the .loc function. This tutorial provides an example of how to use each of these functions in practice. The following code shows how to create a pandas DataFrame and use .iloc to select the column with an index integer value of 3:
🌐
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.
Find elsewhere
🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
pandas: Select rows/columns by index (numbers and names) | note.nkmk.me
August 8, 2023 - You can select and get rows, columns, and elements in pandas.DataFrame and pandas.Series by index (numbers and names) using [] (square brackets). Select columns by column numbers/names using [][Column ...
🌐
sqlpey
sqlpey.com › python › pandas-select-multiple-columns
Pandas: Select Multiple Columns by Name or Index - sqlpey
July 25, 2024 - The .iloc accessor is strictly label-location based and allows selection by integer position. # Select the first two columns (index 0 and 1) selected_columns_by_iloc = df.iloc[:, 0:2] # Slices up to, but not including, index 2 print(selected_columns_by_iloc) # Select specific columns by their index positions (e.g., 0 and 2) specific_iloc = df.iloc[:, [0, 2]] print(specific_iloc)
🌐
Shane Lynn
shanelynn.ie › home › pandas iloc and loc – quickly select rows and columns in dataframes
Pandas iloc and loc – quickly select data in DataFrames
October 16, 2021 - Multiple columns and rows can be selected together using the .iloc indexer. There’s two gotchas to remember when using iloc in this manner: Note that .iloc returns a Pandas Series when one row is selected, and a Pandas DataFrame when multiple rows are selected, or if any column in full is selected. To counter this, pass a single-valued list if you require DataFrame output. When using .loc, or .iloc, you can control the output format by passing lists or single values to the selectors.
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-select-multiple-columns-in-a-pandas-dataframe
How to select multiple columns in a pandas dataframe - GeeksforGeeks
November 30, 2023 - It then selects and displays three rows (index 1 to 3) while extracting specific columns ('Name' and 'Qualification') using the loc method for label-based indexing. ... # 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 three rows and two columns df.loc[1:3, ['Name', 'Qualification']]
🌐
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 ... 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)....
🌐
YouTube
youtube.com › watch
Select Columns of pandas DataFrame by Index in Python (2 Examples) | Extract One Or Multiple Columns - YouTube
How to extract particular pandas DataFrame columns by their index position in the Python programming language. More details: https://statisticsglobe.com/sele...
Published: June 27, 2022
🌐
W3docs
w3docs.com › home › code snippets › python › selecting multiple columns in a pandas dataframe
Selecting multiple columns in a Pandas dataframe | W3docs
To select multiple columns in a pandas DataFrame, you can pass a list of column names to the indexing operator [].
🌐
Towards Data Science
towardsdatascience.com › home › data science › selecting multiple columns from a pandas dataframe
Selecting Multiple Columns From a Pandas DataFrame | Towards Data Science
September 1, 2021 - In today's short guide we showcased a few possible ways for selecting multiple columns from a pandas DataFrame. We discussed how to do so using simple indexing, iloc, loc and through the creation of a new DataFrame.
🌐
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).
🌐
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....