python - 如何从数据框中获取每个月的最后一天并从数据框中删除其余日期?

标签 python pandas dataframe

enter image description here

大家好, 图片是我正在学习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.GrouperDate 分组来过滤月份的最后几天设置为一个月,然后从每组中获取最后一行:

df.loc[df.groupby(pd.Grouper(key='Date', freq='1M')).Date.idxmax()]

关于python - 如何从数据框中获取每个月的最后一天并从数据框中删除其余日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68239023/

相关文章:

r - 如何根据 R 中的向量从 data.frame 中提取值?

r - 检查一个向量中的值是否小于另一向量(不同长度)中的值,并用 Y/N 答案填充表格

python - 在添加到现有键的同时更新 python 字典?

python - 从 Python 调用 AWS Rekognition HTTP API 的示例

Python对数字,'n'中的数字求和

python - Pandas:根据集合中的项目数量进行选择

python - 在 pandas dataframe python 中使用 pii 匿名化特定列

python - 计算 Pandas 中的行数(换行符)

python - 根据两列和各自的范围值创建计数矩阵 pandas

python - 从 gzip 文件写入未压缩文件的内存有效方法