Reputation: 25
I have a csv with a few dozen columns that are all unnamed by default and about half of which need to be removed. I've figured out how to name the columns upon import. Example:
df = pandas.read_csv('ColumnNameTest.csv', names=['ID', 'Name', 'Flavor'])
And I think I figured out how to drop columns:
df.drop('Flavor', axis='columns', inplace=True)
But what is the most efficient way to drop about a dozen columns and insert the column names? Do I have to name all the columns first, then just drop them?
Upvotes: 0
Views: 53
Reputation: 2583
If you want to drop alot of columns and keep some, you can use iloc to select a subset of columns:
df.iloc[:,[3,5,9,10]]
#then name all columns that left
df.columns=['col3','col5','col9','col10']
Or keep a range of columns:
df.iloc[:,3:9]
Upvotes: 1