Matt Matt - 1 year ago 191
Python Question

Deleting all columns except a few python-pandas

Say I have a data table

1 2 3 4 5 6 .. n
A x x x x x x .. x
B x x x x x x .. x
C x x x x x x .. x

And I want to slim it down so that I only have, say, columns 3 and 5 deleting all other and maintaining the structure. How could I do this with pandas? I think I understand how to delete a single column, but I don't know how to save a select few and delete all others.


Answer Source

If you have a list of columns you can just select those:

In [11]: df
   1  2  3  4  5  6
A  x  x  x  x  x  x
B  x  x  x  x  x  x
C  x  x  x  x  x  x

In [12]: col_list = [3, 5]

In [13]: df = df[col_list]

In [14]: df
   3  5
A  x  x
B  x  x
C  x  x
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download