Suppose I have a DataFrame like this:
>>> df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['a','b','b'])
>>> df
a b b
0 1 2 3
1 4 5 6
2 7 8 9
And I want to remove second 'b'
column. If I just use del
statement, it'll delete both 'b'
columns:
>>> del df['b']
>>> df
a
0 1
1 4
2 7
I can select column by index with .iloc[]
and reassign DataFrame, but how can I delete only second 'b'
column, for example by index?
Pandas Drop Multiple Columns By Index You can use df. columns[[index1, index2, indexn]] to identify the list of column names in that index position and pass that list to the drop method. Note that an index is 0 based. Use 0 to delete the first column and 1 to delete the second column and so on.
Pandas DataFrame reset_index() Method The reset_index() method allows you reset the index back to the default 0, 1, 2 etc indexes. By default this method will keep the "old" idexes in a column named "index", to avoid this, use the drop parameter.
df = df.drop(['b'], axis=1).join(df['b'].ix[:, 0:1])
>>> df
a b
0 1 2
1 4 5
2 7 8
Or just for this case
df = df.ix[:, 0:2]
But I think it has other better ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With