大家好, 图片是我正在学习python的数据框。
从这个数据框中,我试图找到每年 12 月最后一天的行记录。我的目标是保持记录在数据框中以黄色突出显示并删除白色行。
例如,对于 2010 年,我只想保留第 3 条记录并删除第 1 行到第 2 行。 至于 2011 年,我想删除第 4 到 7 行并保留第 8 行。
下面是我写的代码。我打算使用循环来查找我要保留的记录并删除其余记录。
为了保留使用月份值的记录,我设法通过保留 Dec 并删除 Jan 到 Nov 的记录来实现我的目标
然而,几天来(最后 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]
最佳答案
这是一个 oneliner,它将通过使用 pd.Grouper
按 Date
分组来过滤月份的最后几天设置为一个月,然后从每组中获取最后一行:
df.loc[df.groupby(pd.Grouper(key='Date', freq='1M')).Date.idxmax()]
关于python - 如何从数据框中获取每个月的最后一天并从数据框中删除其余日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68239023/