0

I have to drop some columns, sometimes the columns name is hart to type, so I want to get a list or tuple or array with the corresponding serial number, then I can drop them with df1.drop(df1.columns[[0, 1, 3]], axis=1).

What is the fast way with pandas to do it like this?

In [2]: df1.columns
Out[2]: Index(['Unnamed: 0', 'Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3', '上班', '下班',
       '上班.1', '下班.1', 'Unnamed: 8', 'Unnamed: 9', 'Unnamed: 10',
       'Unnamed: 11'],
        dtype='object'
In [3]: a = df1.columns.tolist()
        b = list(range(len(df1.columns)))
        tuple(zip(a, b))
Out[3]: (('Unnamed: 0', 0),
        ('Unnamed: 1', 1),
        ('Unnamed: 2', 2),
        ('Unnamed: 3', 3),
        ('上班', 4),
        ('下班', 5),
        ('上班.1', 6),
        ('下班.1', 7),
        ('Unnamed: 8', 8),
        ('Unnamed: 9', 9),
        ('Unnamed: 10', 10),
        ('Unnamed: 11', 11))
In [4]: df1.drop(df1.columns[6:], axis=1)
2
  • Thanks. It returns AttributeError: 'list' object has no attribute 'enumerate', Shoud I do this list(enumerate(df1.columns.tolist()))?
    – Scott Ming
    Sep 7, 2016 at 4:24
  • Sorry, that was my mistake. I can't edit the former post, so I deleted it. enumerate is actually a built-in function, not a method of list objects. See here.
    – vmg
    Sep 7, 2016 at 4:27

1 Answer 1

0

Finally, I found a way to do it fast and easy:

for i, element in enumerate(df.columns):
    print(i, element)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.