How do I delete columns by criteria?
Suppose it df
is a pandas object DataFrame
.
How do I remove all columns
df
containing onlyNone
blank lines or lines with a space?
The rejection criterion can be expressed as those columns where all values are given True
when applied to the following test function:
lambda x: (x is None) or not re.match('\S', str(x))
source to share
You can use applymap
to apply your function to elements DataFrame
:
In [19]: df = pd.DataFrame({'a': [None] * 4, 'b': list('abc') + [' '],
'c': [None] + list('bcd'), 'd': range(7, 11),
'e': [' '] * 4})
In [20]: df
Out[20]:
a b c d e
0 None a None 7
1 None b b 8
2 None c c 9
3 None d 10
In [21]: to_drop = df.applymap(
lambda x: (x is None) or not re.match('\S', str(x))).all()
In [22]: df.drop(df.columns[to_drop], axis=1)
Out[22]:
b c d
0 a None 7
1 b b 8
2 c c 9
3 d 10
source to share
Basically I figured it out, but I'm not familiar with RegEx in Python yet. This is the basic approach I would take:
Dummy Data:
In [1]: df
Out[1]:
a b c
0 None 1
1 b 2
2 c x 3
3 d 4
4 e z 5
In [2]: df.to_dict()
Out[2]:
{'a': {0: None, 1: 'b', 2: 'c', 3: 'd', 4: 'e'},
'b': {0: ' ', 1: ' ', 2: 'x', 3: ' ', 4: 'z'},
'c': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}}
Apply lambda testing for the conditions you want to remove:
In [3]: df.apply(lambda x: x.isin([None,""," "]))
Out[3]:
a b c
0 True True False
1 False True False
2 False False False
3 False True False
4 False False False
Call a method any()
that checks for True on any df column
In [4]: df.apply(lambda x: x.isin([None,""," "])).any()
Out[4]:
a True
b True
c False
Df.columns index with boolean series on top to get the columns you want to delete:
In [5]: drop_cols = df.columns[df.apply(lambda x: x.isin([None,""," "])).any()]
In [6]: drop_cols
Out[6]: Index([a, b], dtype=object)
Use the df.drop () method and pass the axis = 1 option to work with columns:
In [7]: df.drop(drop_cols, axis=1)
Out[7]:
c
0 1
1 2
2 3
3 4
4 5
Now, if anyone with more Pandas / RegEx experience can understand this part, I would say you have a decent solution.
source to share