Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅筛选当月的数据集_Python_Python 3.x_Pandas_Datetime - Fatal编程技术网

Python 仅筛选当月的数据集

Python 仅筛选当月的数据集,python,python-3.x,pandas,datetime,Python,Python 3.x,Pandas,Datetime,我有一个数据集,其中一列包含日期(例如09/17/20)作为对象。我想根据当前月份过滤我的所有行 import pandas as pd import datetime as  dt from datetime import datetime df =  pd.read_csv("dataset.csv", dtype="unicode")  now = datetime.now() df['month_start'] = pd.to_dateti

我有一个
数据集
,其中一列包含日期(例如09/17/20)作为对象。我想根据当前月份过滤我的所有行

import pandas as pd
import datetime as  dt
from datetime import datetime    
df =  pd.read_csv("dataset.csv", dtype="unicode") 
now = datetime.now()
df['month_start'] = pd.to_datetime(df['month_start'], format = "%Y-%d-%m")
mask = df['month_start'].dt.strftime("%Y-%m") == datetime.today().strftime("%Y-%m")
include = df[mask]
df.to_csv("dates.csv")
print(datetime.today().strftime("%Y-%m"))

我的尝试根本不过滤日期,因为我只希望当前月份的行。

请检查代码片段

我从
dataframe
中提取所有月份并将其存储在一个列表中,提取所有年份并存储在另一个列表中,然后将该列表与当前月份和当前年份进行比较,然后从两个列表中访问公共值,最后使用索引值使用
iloc
定位给定行

import pandas as pd
from datetime import datetime
df =  pd.read_csv("data.csv", dtype="unicode") 
amon = pd.DatetimeIndex(df['month_start']).month.tolist()
ayear= pd.DatetimeIndex(df['month_start']).year.tolist()
bmon=[i for i,x in enumerate(amon) if((x==datetime.now().month))]
byear=[i for i,x in enumerate(ayear) if((x==datetime.now().year))]
common = [i for i in bmon if i in byear]
df=df.iloc[common]

对不起,我忘了提到我有2015年的数据。您的代码片段只过滤月份,而不是根据当前月份和年份过滤数据的年份@阿伦。请编辑您的问题以使其更易于理解是的,请仅针对当月
Input
   month_start
0   08/17/2015
1   09/17/2015
2   09/17/2020
3   07/17/2020
4   06/17/2020

Output
  month_start
2    09/17/2020