[英]Select rows in pandas dataframe if all the columns contain certain pattern
I have following dataframe 我有以下数据框
id pattern1 pattern2 pattern3
1 a-b-c a-b-- a-b-c
2 a-a-- a-b-- a-c--
3 a-v-- a-m-- a-k--
4 a-b-- a-n-- a-n-c
I want to filter rows that contains the pattern -- at the end in all the columns. 我想过滤包含模式的行-在所有列的末尾。 In this case the output would be 在这种情况下,输出将是
2 a-a-- a-b-- a-c--
3 a-v-- a-m-- a-k--
So far I can only think of doing something like the following 到目前为止,我只能考虑做以下事情
df[(len(df['pattern1'].str.split('--')[1])==0) & \
(len(df['pattern2'].str.split('--')[1])==0) & \
(len(df['pattern3'].str.split('--')[1])==0)]
This doesn't work.Also,I can't write the names of all the columns as tehre are 20 columns. 这是行不通的。此外,我无法写所有列的名称,因为这是20列。 How can I filter rows where all the columns in that row match certain pattern/condition? 在该行中所有列均符合特定模式/条件的情况下,如何过滤行?
Start with setting "id" as the index, if not yet done. 首先将“ id”设置为索引(如果尚未完成)。
df = df.set_index('id')
One option to check each string is using applymap
calling str.endswith
: 检查每个字符串的一种方法是使用applymap
调用str.endswith
:
df[df.applymap(lambda x: x.endswith('--')).all(1)]
pattern1 pattern2 pattern3
id
2 a-a-- a-b-- a-c--
3 a-v-- a-m-- a-k--
Another option is apply
calling pd.Series.str.endswith
for each column: 另一个选择是对每列apply
调用pd.Series.str.endswith
:
df[df.apply(lambda x: x.str.endswith('--')).all(1)]
pattern1 pattern2 pattern3
id
2 a-a-- a-b-- a-c--
3 a-v-- a-m-- a-k--
Lastly, for performance, you can AND masks inside a list comprehension using logical_and.reduce
: 最后,为了提高性能,您可以使用logical_and.reduce
对列表理解内的AND掩码:
# m = np.logical_and.reduce([df[c].str.endswith('--') for c in df.columns])
m = np.logical_and.reduce([
[x.endswith('--') for x in df[c]] for c in df.columns])
m
# array([False, True, True, False])
df[m]
pattern1 pattern2 pattern3
id
2 a-a-- a-b-- a-c--
3 a-v-- a-m-- a-k--
If there are other columns, but you only want to consider those named "pattern*", you can use filter
on the DataFrame: 如果还有其他列,但您只想考虑那些名为“ pattern *”的列,则可以在DataFrame上使用filter
:
u = df.filter(like='pattern')
Now repeat the options above using u
, for example, the first option will be 现在,使用u
重复上述选项,例如,第一个选项是
df[u.applymap(lambda x: x.endswith('--')).all(1)]
...and so on. ...等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.