在pandas中过滤行

2024-09-27 17:38:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找到那些

  • 代码中的模式AA
  • 代码中的模式__
  • 代码中的数字

数据集如下所示:

User_ID       CODE

A12          AAada __fa
F453         21 ads
J43          Has AA 
...          ...
H21          MNasdf
L32          sad 21
M54          43__12 asd
...          ...

我应该做的是:

  • 首先查找代码中包含AA的所有用户ID,即A12和J43
  • 查找代码中有__的所有用户,即A12和M54
  • 查找代码中包含数字的所有用户,即F453、L32和M54

我已经尝试过使用regex对用户进行过滤,如果是数字,则使用^[^0-9]*$(但也可以使用df.CODE.str.contains('^\d+\'),如果是__,则使用/[$-/:-?{-~!"^_[]]/


Tags: 数据代码用户id模式code数字aa
2条回答

您可以使用|(或)with str.contains()with |分隔三种模式:

df = df[df['CODE'].str.contains('\d|__|AA')]

Out[3]: 
  User_ID        CODE
0     A12  AAada __fa
1    F453      21 ads
2     J43      Has AA
5     L32      sad 21
6     M54  43__12 asd

可以对序列series.str.contains()使用字符串访问器。这是user guide

以及解决方案的代码

pats = ['AA', '__', '\d']
mask = {}
for pat in pats:
    mask[pat] = df.CODE.str.contains(pat, regex=True)
        # regex=True is default, shown here for demonstration
    
    print()
    print(mask[pat])

输出

0     True
1    False
2     True
3    False
4    False
5    False
Name: CODE, dtype: bool

0     True
1    False
2    False
3    False
4    False
5     True
Name: CODE, dtype: bool

0    False
1     True
2    False
3    False
4     True
5     True
Name: CODE, dtype: bool

以后可以使用这些掩码中的每一个来过滤数据帧。在这种情况下,最好将它们作为单独的遮罩,因为它们似乎有重叠

相关问题 更多 >

    热门问题