大家好, 该图像是我学习python的数据框架
从这个数据框中,我试图找到每年12月最后一天的行记录。我的目标是在数据框中以黄色突出显示记录,并删除白色行
例如,对于2010年,我只想保留第三条记录并删除第1到第2行。 至于2011年,我想删除第4行到第7行,保留第8行
下面是我写的代码。我打算使用loop查找我想要保留的记录,并删除其余的记录
为了使用月值保留记录,我通过保留12月和删除1月到11月的记录来实现我的目标
然而,有好几天(最后3行代码),我意识到最后一天并不总是以数据帧中的31结尾,我不能使用我的初始逻辑来删除
我是否可以寻求帮助,如果有更好的解决方案,找到数据帧中的最后一天,并删除其余的
谢谢
amalgamate=pd.read_excel("amalgamate.xlsx")
##Create last 3 columns to segregate Year, Month and Day.
amalgamate["Date"] = pd.to_datetime(amalgamate["Date"], errors = "raise", format = "%Y-%m-%d")
amalgamate["Year"]=amalgamate["Date"].dt.year
amalgamate["Month"]=amalgamate["Date"].dt.month
amalgamate["Day"]=amalgamate["Date"].dt.day
listofMonth=amalgamate.Month.unique()
listofDay=amalgamate.Day.unique()
#Loop through the records and remove records that are not Dec for each year
for eachmonth in listofMonth:
if eachmonth !=12:
amalgamate=amalgamate[amalgamate.Month != eachmonth]
#Loop through the records and remove records that are not 31 for each month
for eachday in listofDay:
if eachday !=31:
amalgamate=amalgamate[amalgamate.Day != eachday]
您可以使用pandas groupby查找每年的最后一个月(即最大)和最后一天,然后合并数据帧以仅筛选包含最后一个月和最后一天的行。正如您不必假设数据中12月的最后一天是31日一样,您也不必假设数据中一年的最后一个月是12月。有多种方法可以做到这一点,您可以按不同的顺序执行以下步骤。以下是我认为最容易遵循的一条:
下面是一个oneliner,它将通过按} 设置为一个月来过滤月份的最后几天,然后从每个组中获取最后一行:
Date
分组并将^{正如您在问题开头提到的,您希望查找每年12月的最后一天,您可以按年份分组日期,并按^{} 获取组内的最后一个条目,如下所示:
如果您还想查找一个月的最后一天(如您在问题末尾所述),可以按年份和月份对日期进行分组,并按^{} 获取组中的最后一个条目,如下所示:
相关问题 更多 >
编程相关推荐