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
To select a single column, use square brackets [] with the column name of the column of interest. For more explanation, see Brackets in Python and pandas.
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 › pandas › pandas-select-columns
Pandas Select Columns - GeeksforGeeks
July 23, 2025 - Simplest way to select a specific or multiple columns in pandas dataframe is by using bracket notation, where you place the column name inside square brackets.
🌐
Pandas
pandas.pydata.org › docs › user_guide › indexing.html
Indexing and selecting data — pandas 3.0.6 documentation
You can pass a list of columns to [] to select columns in that order. If a column is not contained in the DataFrame, an exception will be raised.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.select_dtypes.html
pandas.DataFrame.select_dtypes — pandas 3.0.6 documentation
With pd.options.future.infer_string enabled, using "str" will work to select all string columns. See the numpy dtype hierarchy · To select datetimes, use np.datetime64, 'datetime' or 'datetime64' To select timedeltas, use np.timedelta64, 'timedelta' or 'timedelta64' To select Pandas categorical dtypes, use 'category' To select Pandas datetimetz dtypes, use 'datetimetz' or 'datetime64[ns, tz]' Examples ·
🌐
Medium
medium.com › @amit25173 › pandas-subset-columns-guide-071e2533918d
Pandas Subset Columns Guide. I understand that learning data science… | by Amit Yadav | Medium
March 6, 2025 - The same applies to working with DataFrames in pandas. Instead of dealing with every column, you can subset only the ones that matter. ... The simplest way to select columns in pandas is by using square brackets [].
🌐
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
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 - print(df[['col_2']]) ... ... You can also use loc to specify a slice based on column names, and iloc to select columns by their numbers, either individually or as a range (list or slice)....
🌐
APXML
apxml.com › courses › essential-numpy-pandas › chapter-7-data-selection-indexing-pandas › selecting-columns
Select Columns Pandas DataFrame
Important observation: When you select multiple columns using a list within the brackets [['Col1', 'Col2']], the result is a new DataFrame containing only the specified columns, in the order you listed them. Pandas also allows accessing a single column using dot notation, similar to accessing ...
🌐
DataCamp
datacamp.com › tutorial › python-select-columns
Python Pandas Select Columns Tutorial | DataCamp
November 25, 2024 - You can also use loc to select all rows but only a specific number of columns. Simply replace the first list that specifies the row labels with a colon. A slice going from beginning to end. This time, we get back all of the rows but only two columns. ... country capital BR Brazil Brasilia RU Russia Moscow IN India New Delhi CH China Beijing SA South Africa Pretoria · The iloc function allows you to subset pandas DataFrames based on their position or index.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › indexing-and-selecting-data-with-pandas
Indexing and Selecting Data with Pandas - GeeksforGeeks
To select all rows and specific columns, use a colon [:] for all rows and a list of column positions: ... Pandas also provides several other methods that we may find useful for indexing and manipulating DataFrames:
Published: April 28, 2026
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.columns.html
pandas.DataFrame.columns — pandas 3.0.6 documentation
This property holds the column names as a pandas Index object. It provides an immutable sequence of column labels that can be used for data selection, renaming, and alignment in DataFrame operations.
🌐
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 all columns between hornets and nets df.loc[:, 'hornets':'nets'] hornets spurs nets 0 5 10 10 1 7 12 14 2 7 14 25 3 9 13 22 4 12 13 25 5 9 19 17 6 14 22 12 · All of the columns between the names ‘hornets’ and ‘nets’ are returned. The following tutorials explain how to perform other common tasks in pandas:
🌐
Python.org
discuss.python.org › python help
Selecting a column by integer in Pandas - Python Help - Discussions on Python.org
May 5, 2023 - Hello, I am encountering an issue with selecting a column by integer in Pandas. The syntax used by the course instructor is in the code below. The data is provided. I see in a video that this syntax works for them. I’m …
🌐
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:
🌐
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).
🌐
Saturn Cloud
saturncloud.io › blog › how-to-select-columns-and-rows-in-pandas-without-column-or-row-names
How to Select Columns and Rows in Pandas Without Column or Row Names | Saturn Cloud Blog
May 1, 2026 - You need to extract specific columns and rows based on their position in the DataFrame, but you don’t know their names. To select columns without column names, you can use the iloc method in Pandas.
🌐
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 - This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series.
🌐
Machine Learning Plus
machinelearningplus.com › blog › pandas select columns
Pandas Select Columns - machinelearningplus
March 8, 2022 - Here also, you can leave row slicing ... columns to be selected. ... You can use the filter function of the pandas dataframe to select columns containing a specified string in column names....
🌐
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
Alternatively, you can assign all ... 'residual_sugar'] wine_list_four = wine_four[cols] To select columns using select_dtypes method, you should first find out the number of columns for each data types....