How to select all columns except one in pandas?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC H Dvoks String Quartet No 12 Ame
--
Chapters
00:00 Question
00:26 Accepted answer (Score 727)
00:46 Answer 2 (Score 397)
01:47 Answer 3 (Score 208)
02:00 Answer 4 (Score 142)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/2976...
Answer 1 links:
[deprecated]: https://pandas-docs.github.io/pandas-doc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas
#avk47
--
Track title: CC H Dvoks String Quartet No 12 Ame
--
Chapters
00:00 Question
00:26 Accepted answer (Score 727)
00:46 Answer 2 (Score 397)
01:47 Answer 3 (Score 208)
02:00 Answer 4 (Score 142)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/2976...
Answer 1 links:
[deprecated]: https://pandas-docs.github.io/pandas-doc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas
#avk47
ACCEPTED ANSWER
Score 788
When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:
df.loc[:, df.columns != 'b']
a c d
0 0.561196 0.013768 0.772827
1 0.882641 0.615396 0.075381
2 0.368824 0.651378 0.397203
3 0.788730 0.568099 0.869127
ANSWER 2
Score 449
Don't use ix. It's deprecated. The most readable and idiomatic way of doing this is df.drop():
>>> df.drop('b', axis=1)
a c d
0 0.418762 0.869203 0.972314
1 0.991058 0.594784 0.534366
2 0.407472 0.396664 0.894202
3 0.726168 0.324932 0.906575
Note that by default, .drop() does not operate inplace; despite the ominous name, df is unharmed by this process. If you want to permanently remove b from df, do df.drop('b', inplace=True).
df.drop() also accepts a list of labels, e.g. df.drop(['a', 'b'], axis=1) will drop column a and b.
ANSWER 3
Score 229
df[df.columns.difference(['b'])]
Out:
a c d
0 0.427809 0.459807 0.333869
1 0.678031 0.668346 0.645951
2 0.996573 0.673730 0.314911
3 0.786942 0.719665 0.330833
ANSWER 4
Score 150
You can use df.columns.isin()
df.loc[:, ~df.columns.isin(['b'])]
When you want to drop multiple columns, as simple as:
df.loc[:, ~df.columns.isin(['col1', 'col2'])]