xkcd xkcd - 4 months ago 39
Python Question

How to drop a column in a Pandas DataFrame which contains the same value

I have a Pandas DataFrame with some columns that have the same value in every row.

So something like:-

Col1 Col2 Col3 .... ColX ColY ColZ
323 False 324 4 abc Sync
232 False 342 4 def Sync
364 False 2343 4 ghi Sync

So I would like to drop Col2, ColX and ColZ from the above DataFrame.


You can compare the DataFrame against a particular row (I chose the first one with df.iloc[0]) and use loc to select the columns that satisfy the condition you specified:

df.loc[:, ~(df == df.iloc[0]).all()]
   Col1  Col3 ColY
0   323   324  abc
1   232   342  def
2   364  2343  ghi