Skip to main content
 首页 » 编程设计

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

2025年05月04日30Terrylee

如何打印数据框中的所有日期(解析为字符串),其中字符串中包含 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