Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.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 当月份不存在时,如何在datetimeindex中获取每个月的第一天';t以01开头?_Python_Pandas_Datetimeindex - Fatal编程技术网

Python 当月份不存在时,如何在datetimeindex中获取每个月的第一天';t以01开头?

Python 当月份不存在时,如何在datetimeindex中获取每个月的第一天';t以01开头?,python,pandas,datetimeindex,Python,Pandas,Datetimeindex,我有一个带有DateTimeIndex的数据框,持续了10年,一天一天。我需要提取对应于每个月第一天的行。但是,并非所有月份都以01开头,有些月份以02、03、04等开头 2020-01-02 2020-01-03 ... 2020-01-31 2020-02-03 ... 2020-02-29 2020-03-02 预期df必须为: 2020-01-02 2020-02-03 2020-03-02 有什么建议吗?在几个月内使用,然后在几个月的头几天使用反向面具测试复制品并过滤: #if n

我有一个带有DateTimeIndex的数据框,持续了10年,一天一天。我需要提取对应于每个月第一天的行。但是,并非所有月份都以01开头,有些月份以02、03、04等开头

2020-01-02
2020-01-03
...
2020-01-31
2020-02-03
...
2020-02-29
2020-03-02
预期df必须为:

2020-01-02
2020-02-03
2020-03-02
有什么建议吗?

在几个月内使用,然后在几个月的头几天使用反向面具测试复制品并过滤:

#if necessary
df = df.sort_index()

print (df)
            A
date         
2020-01-02  4
2020-01-03  9
2020-01-31  2
2020-02-03  7
2020-02-29  3
2020-03-02  1

df1 = df[~df.index.to_period('m').duplicated()]
print (df1)
            A
date         
2020-01-02  4
2020-02-03  7
2020-03-02  1
详细信息

print (df.index.to_period('m'))
PeriodIndex(['2020-01', '2020-01', '2020-01', '2020-02', '2020-02', '2020-03'], 
            dtype='period[M]', name='date', freq='M')

print (df.index.to_period('m').duplicated())
[False  True  True False  True False]

print (~df.index.to_period('m').duplicated())
[ True False False  True False  True]
另一个解决方案是使用:


您可以从如下日期中提取月份:

df["d"] = pd.to_datetime(df.d)
df["month"] = df.d.dt.month

df
           d  month
0 2020-01-02      1
1 2020-01-03      1
2 2020-01-31      1
3 2020-02-03      2
4 2020-02-29      2
5 2020-03-02      3
然后按月分组,取组中的第一个元素:

df.groupby("month").first()

               d
month           
1     2020-01-02
2     2020-02-03
3     2020-03-02

如果我得到了
AttributeError:'Index'对象没有属性'to_period'
,我做错了什么?@keru laeda86-没有datetimeIndex,所以需要
df.Index=pd.to_datetime(df.Index)
@keru laeda86-如果
date
是列,使用
df['date']=pd.to_datetime(df['date'])
,然后
df[~df'date']dt.to_period('m')).duplicated()
df.groupby("month").first()

               d
month           
1     2020-01-02
2     2020-02-03
3     2020-03-02