Pandas: Get all columns that have constant value
Use the pandas not-so-well-known builtin nunique()
:
df.columns[df.nunique() <= 1]
Index(['B', 'C'], dtype='object')
Notes:
- Use
nunique(dropna=False)
option if you want na's counted as a separate value - It's the cleanest code, but not the fastest. (But in general code should prioritize clarity and readability).
try this,
print [col for col in df.columns if len(df[col].unique())==1]
Output:
['B', 'C']
You can use set
and apply a filter on a series:
vals = df.apply(set, axis=0)
res = vals[vals.map(len) == 1].index
print(res)
Index(['B', 'C'], dtype='object')
Use res.tolist()
if having a list output is important.
Solution 1:
c = [c for c in df.columns if len(set(df[c])) == 1]
print (c)
['B', 'C']
Solution 2:
c = df.columns[df.eq(df.iloc[0]).all()].tolist()
print (c)
['B', 'C']
Explanation for Solution 2:
First compare all rows to the first row with DataFrame.eq
...
print (df.eq(df.iloc[0]))
A B C D
0 True True True True
1 False True True False
2 False True True False
... then check each column is all True
s with DataFrame.all
...
print (df.eq(df.iloc[0]).all())
A False
B True
C True
D False
dtype: bool
... finally filter columns' names for which result is True:
print (df.columns[df.eq(df.iloc[0]).all()])
Index(['B', 'C'], dtype='object')
Timings:
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(1000,100)))
df[np.random.randint(100, size=20)] = 100
print (df)
# Solution 1 (second-fastest):
In [243]: %timeit ([c for c in df.columns if len(set(df[c])) == 1])
3.59 ms ± 43.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# Solution 2 (fastest):
In [244]: %timeit df.columns[df.eq(df.iloc[0]).all()].tolist()
1.62 ms ± 13.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
#Mohamed Thasin ah solution
In [245]: %timeit ([col for col in df.columns if len(df[col].unique())==1])
6.8 ms ± 352 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
#jpp solution
In [246]: %%timeit
...: vals = df.apply(set, axis=0)
...: res = vals[vals.map(len) == 1].index
...:
5.59 ms ± 64.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
#smci solution 1
In [275]: %timeit df.columns[ df.nunique()==1 ]
11 ms ± 105 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
#smci solution 2
In [276]: %timeit [col for col in df.columns if not df[col].is_unique]
9.25 ms ± 80 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
#smci solution 3
In [277]: %timeit df.columns[ df.apply(lambda col: not col.is_unique) ]
11.1 ms ± 511 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)