簡體   English   中英

Select python python dataframe 中的最近日期

[英]Select nearest date first day of month in a python dataframe

我有這種 dataframe
在此處輸入圖像描述

這些數據代表消費指數的值,通常每月編碼一次(在月底或下個月月初),但有時更多。 如果計數器不可用並被更換,該值可以重置為“0”。 此外,有些月沒有可用的數據。

我希望 select 每個月只有一個條目,但這個條目必須最接近該月的第一天並且低於該月的第 15 天(因為如果這一天更高,它可能是衡量月)。 另一個條件是,如果兩個值之間的差為負(計數器已被替換),則即使日期不是靠近月份第一天的最近日,也需要保留該值。

例如output數據需要
在此處輸入圖像描述

目的是僅計算每月的消費量。

一種解決方案是解析 dataframe(作為數組)並執行一些 if 條件語句。 但是我想知道是否有“簡單”的替代方案來實現這一目標。

謝謝

您可以使用MonthEnd規范化月份數據,然后根據該列刪除重復項並保留last值。

from pandas.tseries.offsets import MonthEnd    
df.New = df.Index + MonthEnd(1)
df.Diff = abs((df.Index - df.New).dt.days)
df = df.sort_values(df.New, df.Diff)
df = df.drop_duplicates(subset='New', keep='first').drop(['New','Diff'], axis=1)

這應該可以解決問題,但我無法測試,所以如果這不起作用,請將示例數據復制並粘貼到 StackOverFlow 中。

定義 dataframe,將索引轉換為日期時間,定義輔助列,使用它們運行shift方法有條件地刪除行,最后刪除輔助列:

from pandas.tseries.offsets import MonthEnd, MonthBegin
import pandas as pd
from datetime import datetime as dt
import numpy as np

df = pd.DataFrame([
    [1254],
    [1265],
    [1277],
    [1301],
    [1345],
    [1541]
], columns=["Value"]
, index=[dt.strptime("05-10-19", '%d-%m-%y'),
         dt.strptime("29-10-19", '%d-%m-%y'),
         dt.strptime("30-10-19", '%d-%m-%y'),
         dt.strptime("04-11-19", '%d-%m-%y'),
         dt.strptime("30-11-19", '%d-%m-%y'),
         dt.strptime("03-02-20", '%d-%m-%y')
         ]
)

early_days = df.loc[df.index.day < 15]
early_month_end = early_days.index - MonthEnd(1)
early_day_diff = early_days.index - early_month_end
late_days = df.loc[df.index.day >= 15]
late_month_end = late_days.index + MonthBegin(1)
late_day_diff = late_month_end - late_days.index
df["day_offset"] = (early_day_diff.append(late_day_diff) / np.timedelta64(1, 'D')).astype(int)
df["start_of_month"] = df.index.day < 15
df["month"] = df.index.values.astype('M8[D]').astype(str)
df["month"] = df["month"].str[5:7].str.lstrip('0')
# df["month_diff"] = df["month"].astype(int).diff().fillna(0).astype(int)
df = df[df["month"].shift().ne(df["month"].shift(-1))]
df = df.drop(columns=["day_offset", "start_of_month", "month"])
print(df)

回報:

            Value
2019-10-05   1254
2019-10-30   1277
2019-11-04   1301
2019-11-30   1345
2020-02-03   1541

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM