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
...
🌐
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.
Discussions

How to Optimize Large CSV Processing?
You should try loading the csv with polars. Is not much different than pandas, but faster and since you need to drop the duplicates, the function is simple https://docs.pola.rs/api/python/dev/reference/dataframe/api/polars.DataFrame.unique.html After that you can export to pandas since you are more familiar with it. More on reddit.com
🌐 r/learnpython
19
10
October 23, 2024
Find column names that contain multiple strings at the same time
df[df["account"].str.contains(r'(?=.*creating)(?=.*damage)', regex=True)] or df[df["account"].str.contains('creating') & df["account"].str.contains('damage')] More on reddit.com
🌐 r/learnpython
3
1
January 10, 2022
Pandas - Filter based on multiple conditions
You can filter rows by using "boolean indexing", and as with all boolean expressions you can combine multiple conditions with "and", "or, "any", and "all" operations. Here is an example using "and", the syntax for that is " & "; note that neither condition on it's own would give the results that the conjunction of the 2 conditions does. >>> df = pd.DataFrame({"a":[1, 3, 5], "b":[2, 4, 6], "c":[7, 14, 1]}) >>> df a b c 0 1 2 7 1 3 4 14 2 5 6 1 >>> df[(df.c <= 7)] a b c 0 1 2 7 2 5 6 1 >>> df[(df.a <= 3)] a b c 0 1 2 7 1 3 4 14 >>> df[(df.a <= 3) & (df.c <= 7)] a b c 0 1 2 7 BTW, I don't see how having the column names as a list of strings would be much help, but you _could_ do something using the df["column"] syntax like: >>> def myfilt(df, labels): ... return df[(df[labels[0]] <= 3) & (df[labels[1]] <= 7)] ... >>> control_fields = ["a", "c"] >>> myfilt(df, control_fields) a b c 0 1 2 7 >>> https://pandas-docs.github.io/pandas-docs-travis/user_guide/indexing.html#boolean-indexing More on reddit.com
🌐 r/learnpython
6
1
January 17, 2021
Filter Pandas Dataframe Unnamed column on Multiple values

Hi, I am not a huge fan of the isin() syntax. There is actually a way to do this using .query() but given that your DataFrame does not have column names it is not as elegant.

filter = ["H", "W"]
df2 = pd.DataFrame({"col": df.iloc[:, 31]})
df2 = df2.query("col in @filter")
More on reddit.com
🌐 r/learnpython
3
1
December 20, 2019
🌐
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 - #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:
🌐
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 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']]
🌐
PythonHow
pythonhow.com › how › select-multiple-columns-in-a-pandas-dataframe
Here is how to select multiple columns in a Pandas dataframe in Python
Selecting multiple columns by name: import pandas as pd # create a sample DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}) # select columns A and B df_AB = df[['A', 'B']] print(df_AB)
🌐
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.
🌐
APXML
apxml.com › courses › essential-numpy-pandas › chapter-7-data-selection-indexing-pandas › selecting-columns
Select Columns Pandas DataFrame
Notice that selecting a single column this way returns a Pandas Series object, not a DataFrame. A Series is like a one-dimensional 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, ...
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
I’m interested in the age and ... 1 38.0 female 2 26.0 female 3 35.0 female 4 35.0 male · To select multiple columns, use a list of column names within the selection brackets []....
🌐
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
🌐
Towards Data Science
towardsdatascience.com › home › latest › selecting multiple columns from a pandas dataframe
Selecting Multiple Columns From a Pandas DataFrame | Towards Data Science
January 28, 2025 - The first option you have when comes to select multiple columns from an existing pandas DataFrame is the use of basic indexing.
🌐
Studyopedia
studyopedia.com › home › select multiple columns in a pandas dataframe
Select multiple columns in a Pandas DataFrame - Studyopedia
February 28, 2025 - In a Pandas DataFrame, to select more than one column in a range, mention the index numbers in a range separated by a colon. The following selects columns 3rd to 5th ... Let us see an example to select multiple columns in a range.
🌐
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 - Here is an example to select ‘Age’ and ‘Name’ columns from dataframe using ix function. df1 = df.ix[:,1:3] print(df1) ## Output Age Name 0 27 John 1 24 Jane 2 22 Jim 3 32 Kim · If you call this function in Pandas >0.2, then it will give you an error saying dataframe has no attribute ix.
🌐
Net Informations
net-informations.com › ds › pd › column.htm
How to select multiple columns from Pandas DataFrame
Selecting columns from a Pandas DataFrame can be done using different methods, such as using square brackets [] with column names or a list of column names, using the attribute operator . with the column name, or using the loc and iloc accessors for more advanced selection based on labels or ...
🌐
Saturn Cloud
saturncloud.io › blog › pandas-selecting-multiple-columns-from-one-row
Pandas: Selecting Multiple Columns from One Row | Saturn Cloud Blog
May 1, 2026 - In conclusion, selecting multiple columns from one row in a pandas dataframe is a simple and straightforward process. You can use the loc method to select a specific row and then specify a list of column names to extract the desired information.
🌐
PythonForBeginners.com
pythonforbeginners.com › home › select multiple columns in a pandas dataframe
Select Multiple Columns in a Pandas Dataframe - PythonForBeginners.com
January 30, 2023 - In this example, we have selected the columns at position 1 and 2 using the iloc attribute of the pandas dataframe. If you want to select multiple columns in the pandas dataframe using the column names, you can use the loc attribute.
🌐
Machine Learning Plus
machinelearningplus.com › blog › pandas select columns
Pandas Select Columns - machinelearningplus
March 8, 2022 - One of the most basic ways in pandas to select columns from dataframe is by passing the list of columns to the dataframe object indexing operator. ... The dataframe_name.columns returns the list of all the columns in the dataframe.
🌐
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.
🌐
Squash
squash.io › how-to-select-multiple-columns-in-a-pandas-dataframe
How to Select Multiple Columns in a Pandas Dataframe
October 17, 2023 - Another method to select multiple columns in a pandas dataframe is by using the loc[] method.
🌐
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 ...
🌐
KoalaTea site
koalatea.io › pandas-dataframe-multiple-column
How to Select Multiple Columns in Pandas - KoalaTea
December 14, 2023 - The next way to select columns is using the loc method. This method also allows us to select rows. import pandas as pd df = pd.DataFrame([ { "person": "James", "sales": 1000, }, { "person": "Clara", "sales": 3000, } ]) newDf = df.loc[:, ['pearson', 'sales']] print(newDf.head())