测试匹配或包含模式的字符串

你可以检查是否一个元素包含一个可以匹配到的正则表达式:

  1. In [103]: pattern = r'[0-9][a-z]'
  2. In [104]: pd.Series(['1', '2', '3a', '3b', '03c']).str.contains(pattern)
  3. Out[104]:
  4. 0 False
  5. 1 False
  6. 2 True
  7. 3 True
  8. 4 True
  9. dtype: bool

或者是否元素完整匹配一个正则表达式

  1. In [105]: pd.Series(['1', '2', '3a', '3b', '03c']).str.match(pattern)
  2. Out[105]:
  3. 0 False
  4. 1 False
  5. 2 True
  6. 3 True
  7. 4 False
  8. dtype: bool

matchcontains的区别是是否严格匹配。match严格基于re.match,而contains基于re.search。 类似match, contains, startswithendswith 可以传入一个额外的na参数,因此,因此缺失值在匹配时可以被认为是True或者False

  1. In [106]: s4 = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
  2. In [107]: s4.str.contains('A', na=False)
  3. Out[107]:
  4. 0 True
  5. 1 False
  6. 2 False
  7. 3 True
  8. 4 False
  9. 5 False
  10. 6 True
  11. 7 False
  12. 8 False
  13. dtype: bool