Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas remove column by index

Tags:

python

pandas

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?

like image 699
Roman Pekar Avatar asked Nov 14 '13 09:11

Roman Pekar


People also ask

How do I drop a column in pandas based on 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.

What does reset_index () do in pandas?

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.


1 Answers

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.

like image 187
Puffin GDI Avatar answered Oct 03 '22 16:10

Puffin GDI