Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing multiple columns with the same name except the first one? [duplicate]

Tags:

python

pandas

If you have multiple columns with the same name in a dataframe, how do you remove all of the columns except the first one?

like image 536
Jun Jang Avatar asked Dec 04 '22 22:12

Jun Jang


1 Answers

Let df be a dataframe with two duplicated columns:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=("a","a","b"))
#   a  a  b
#0  1  2  3
#1  4  5  6
#2  7  8  9

Find out which column names are not duplicated, and keep them:

df1 = df.loc[:, ~df.columns.duplicated()]
#   a  b
#0  1  3
#1  4  6
#2  7  9
like image 159
DYZ Avatar answered Dec 11 '22 15:12

DYZ