python - 为什么包含无法选择包含指定字符串的行?

标签 python regex pandas contains

>>> y
1    2002-12-31
2    2003-12-31
3    2004-03-31
4    2004-06-30
Name: report_date, dtype: object

我想提取包含 12-31 的行。

>>> y.str.contains('12-31')
>>> y.str.contains('\.+12-31')
>>> y.str.contains('2002-12-31')

所有三个表达式都得到相同的输出:

1   NaN
2   NaN
3   NaN
4   NaN
Name: report_date, dtype: float64

如何提取包含字符串12-31的行? 我想要的输出:

1   True
2   True
3   NaN
4   NaN

最佳答案

也许列中是日期,所以之前将其转换为字符串:

m = y.astype(str).str.contains('12-31')
print (m)
0     True
1     True
2    False
3    False
Name: report_date, dtype: bool

关于python - 为什么包含无法选择包含指定字符串的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59844205/

相关文章:

python - import skimage 有效,但 skimage.measure 无效

python - 线程与异步图像处理?

java - 日期的正则表达式省略月份部分的一个字符

python - Pandas 多次从 DataFrame 添加值

python - 在 ubuntu 中安装 imutils

python - 正则表达式查找包含 "-"的单词

带有\w 的 Python 正则表达式不起作用

mysql - SQL 正则表达式最后一个字符搜索不起作用

python - 如何将单行数据框连接到更大的数据框?当前获取 "TypeError: Expected tuple, got str"

python - 如何用该列的平均值填充数据框中的空白(Nan)?