If you have multiple columns with the same name in a dataframe, how do you remove all of the columns except the first one?
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
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