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)
AttributeError: 'list' object has no attribute 'enumerate'
, Shoud I do thislist(enumerate(df1.columns.tolist()))
?enumerate
is actually a built-in function, not a method of list objects. See here.