Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - Drop multiple columns in pandas

I am trying to drop multiple columns (column 2 and 70 in my data set, indexed as 1 and 69 respectively) by index number in a pandas data frame with the following code:

df.drop([df.columns[[1, 69]]], axis=1, inplace=True)

I get the following error:

TypeError: unhashable type: 'Index'

And in my code the [1, 69] is highlighted and says:

Expected type 'Integral', got 'list[int]' instead

The following code does what I want it to do successfully, but on two lines of repetitive code (first dropping col index 69, then 1, and order does matter because dropping earlier columns changes the index of later columns). I thought I could specify more than one column index simply as a list, but perhaps I have something wrong above?

df.drop([df.columns[69]], axis=1, inplace=True)
df.drop([df.columns[1]], axis=1, inplace=True)

Is there a way that I can do this on one line similar to the first code snippet above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...