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