confused
confused

Reputation: 186

Syntax Error In Python When Trying To Refer To Range Of Columns

I am trying to remove the last several columns from a data frame. However I get a syntax error when I do this:

db = db.drop(db.columns[[12:22]], axis = 1)

This works but it seems clumsy...

db = db.drop(db.columns[[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]], axis = 1)

How do I refer to a range of columns?

Upvotes: 0

Views: 229

Answers (2)

Itamar Mushkin
Itamar Mushkin

Reputation: 2905

Steven Burnap's explanation is correct, but the solution can be simplified - just remove the internal parentheses:

db = db.drop(db.columns[12:22], axis = 1)

this way, db.columns[12:22] is a 'slice' of the columns array (actually index, but doesn't matter here), which goes into the drop method.

Upvotes: 0

user1342784
user1342784

Reputation:

The first example uses [12:22] is a "slice" of nothing. It's not a meaningful statement, so as you say, it gives a syntax error. It seems that what you want is a list containing the numbers 12 through 22. You need to either write it out fully as you did, or use some generator function to create it.

The simplest is range, which is a generator that creates a list of sequential values. So you can rewrite your example like:

db = db.drop(db.columns[list(range(12,23)]], axis = 1)

Though it looks like you are using some sort of library. If you want more detailed control, you need to look the documentation of that library. It seems that db.columns is an object of a class that has defined an array operator. Perhaps that class's documentation shows a way of specifying ranges in a way other than a list.

Upvotes: 1

Related Questions