在dataframe值Python中删除日期的第一个实例
我有一个如下所示的数据帧:在dataframe值Python中删除日期的第一个实例,python,python-3.x,pandas,dataframe,pandas-groupby,Python,Python 3.x,Pandas,Dataframe,Pandas Groupby,我有一个如下所示的数据帧: Publication Date Date Value 2018-01-01 2018-01-01 2 2018-01-01 2018-01-02 13 2018-01-01 2018-01-03 14 2018-01-01 2018-01-04 12 2018-01-0
Publication Date Date Value
2018-01-01 2018-01-01 2
2018-01-01 2018-01-02 13
2018-01-01 2018-01-03 14
2018-01-01 2018-01-04 12
2018-01-02 2018-01-02 1.5
2018-01-02 2018-01-03 14
2018-01-02 2018-01-04 15
2018-01-02 2018-01-05 15.5
2018-01-03 2018-01-03 1.8
2018-01-03 2018-01-04 13
2018-01-03 2018-01-05 17
2018-01-03 2018-01-06 15
.
.
我想删除发布日期更改的每一行数据,因为每次迭代都有非常小的值。输出如下所示:
Publication Date Date Value
2018-01-01 2018-01-02 13
2018-01-01 2018-01-03 14
2018-01-01 2018-01-04 12
2018-01-02 2018-01-03 14
2018-01-02 2018-01-04 15
2018-01-02 2018-01-05 15.5
2018-01-03 2018-01-04 13
2018-01-03 2018-01-05 17
2018-01-03 2018-01-06 15
.
.
数据基本上是这种格式,但包括未显示的额外列(即,日期
按日期+1切换每个出版日期
)
最好的方法是什么?使用:
或者,更一般化,使用或与groupby
:
res = df[df.groupby('PublicationDate').cumcount() > 0]
res = df.groupby('PublicationDate').apply(lambda x: x.tail(len(x)-1))\
.reset_index(drop=True)
print(res)
PublicationDate Date Value
0 2018-01-01 2018-01-02 13.0
1 2018-01-01 2018-01-03 14.0
2 2018-01-01 2018-01-04 12.0
3 2018-01-02 2018-01-03 14.0
4 2018-01-02 2018-01-04 15.0
5 2018-01-02 2018-01-05 15.5
6 2018-01-03 2018-01-04 13.0
7 2018-01-03 2018-01-05 17.0
8 2018-01-03 2018-01-06 15.0
可以将布尔索引与shift一起使用
df[df['Publication Date'] == df['Publication Date'].shift()]
Publication Date Date Value
1 2018-01-01 2018-01-02 13.0
2 2018-01-01 2018-01-03 14.0
3 2018-01-01 2018-01-04 12.0
5 2018-01-02 2018-01-03 14.0
6 2018-01-02 2018-01-04 15.0
7 2018-01-02 2018-01-05 15.5
9 2018-01-03 2018-01-04 13.0
10 2018-01-03 2018-01-05 17.0
11 2018-01-03 2018-01-06 15.0
df[df['Publication Date'] == df['Publication Date'].shift()]
Publication Date Date Value
1 2018-01-01 2018-01-02 13.0
2 2018-01-01 2018-01-03 14.0
3 2018-01-01 2018-01-04 12.0
5 2018-01-02 2018-01-03 14.0
6 2018-01-02 2018-01-04 15.0
7 2018-01-02 2018-01-05 15.5
9 2018-01-03 2018-01-04 13.0
10 2018-01-03 2018-01-05 17.0
11 2018-01-03 2018-01-06 15.0