【问题标题】:Keep only the rows with the first occurring date of each year and month in a pandas DataFrame在 pandas DataFrame 中仅保留具有每年和每月第一次出现日期的行
【发布时间】:2021-12-29 11:44:36
【问题描述】:

我想从 DataFrame 中删除不包括每年和每月 DataFrame 中第一个日期的所有行。这是一个例子:

pd.DataFrame([['2016-02-05', 22], ['2016-02-15', 15], ['2016-05-03', 18], ['2016-05-20', 9], ['2017-03-02', 10], ['2018-04-01', 11], ['2018-04-02', 12]],
             columns=['date', 'qty'])
         date  qty
0  2016-02-05   22
1  2016-02-15   15
2  2016-05-03   18
3  2016-05-20    9
4  2017-03-02   10
5  2018-04-01   11
6  2018-04-02   12

我想让上面的DataFrame变成:

         date  qty
0  2016-02-05   22
2  2016-05-03   18
4  2017-03-02   10
5  2018-04-01   11

我将“日期”列转换为日期时间,并尝试循环执行此操作。但是,我没有到达那里,我确信有比循环执行更有效的方法。感谢您的帮助!

【问题讨论】:

  • 对不起@zyzzler 我不明白你需要什么。

标签: python python-3.x pandas dataframe


【解决方案1】:

另一种方式,可能更快,因为它避免扩展数据框

df.filter(df['date'].dt.to_period('M').drop_duplicates().index, axis = 0)

【讨论】:

    【解决方案2】:

    试试resample:

    #convert to datetime if needed
    df["date"] = pd.to_datetime(df["date"])
    output = df.resample("M", on="date").first().dropna().reset_index(drop=True)
    
    >>> output
            date   qty
    0 2016-02-05  22.0
    1 2016-05-03  18.0
    2 2017-03-02  10.0
    3 2018-04-01  11.0
    

    如果您想保留原始索引,可以这样做:

    output = df.assign(m=df["date"].dt.to_period("m")).drop_duplicates("m").drop("m",axis=1)
    
    >>> output
            date  qty
    0 2016-02-05   22
    2 2016-05-03   18
    4 2017-03-02   10
    5 2018-04-01   11
    

    【讨论】:

    • 工作得很好,谢谢!
    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    相关资源
    最近更新 更多