python - 查找包含特定值的字符串

标签 python string pandas

如何打印数据框中的所有日期(解析为字符串),其中字符串中包含 2012-06

我不记得哪个字符代表“ok after me are random characters, this part is not important”

我以为是 (.*) 但不是

这样做的目的是查找并打开所有 CSV 文件。所以我想我最终可以摆脱这样的事情:2012-06(.*).csv 打开所有 2012 年 6 月的文件并“做事”

import pandas as pd
from datetime import timedelta

datelist = pd.date_range(pd.datetime(year = 2012, month = 6, day = 15), pd.datetime.today()).tolist()
df = pd.DataFrame(datelist)

for date in df[0]:

  d = str(date)

  if d == "2012-06(.*)":  

    print(d)  

最佳答案

我建议使用 Series.str.contains :

df1 = df[df[0].astype(str).str.contains("2012-06")]

Series.str.startswith用于在 Pandas 中过滤:

df1 = df[df[0].astype(str).str.startswith("2012-06")]

print (df1)

            0
0  2012-06-15
1  2012-06-16
2  2012-06-17
3  2012-06-18
4  2012-06-19
5  2012-06-20
6  2012-06-21
7  2012-06-22
8  2012-06-23
9  2012-06-24
10 2012-06-25
11 2012-06-26
12 2012-06-27
13 2012-06-28
14 2012-06-29
15 2012-06-30

关于python - 查找包含特定值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55920023/

相关文章:

python - 如何将页面的功能连接到 qwizard 的下一步按钮?

python - Sucess_url 基于来自 urls.py 的 GenericView 中的 pk

Python - 从字符串中删除前 5 个字符 - 如何获取新的较短字符串?

python - 在 python 脚本中删除所有 WS 字符不起作用

python - Python 有流式正则表达式模块吗?

python - 在不包括当前行的两列之间创建一个带有 pandas groupby 划分的新列

python - 在 numpy/pandas 中生成相关数

python - 将多个 lambda 函数与 pandas 数据框一起使用

python - qt设计器如何创建彩色面板?

string - 为什么使用 const 字符串参数时程序会崩溃?