【问题标题】:Count rows based on year-month and sort it from oldest to newest根据年月计算行数并从最旧到最新排序
【发布时间】:2021-10-19 20:21:31
【问题描述】:

我有一个这样的 df:

data = {'date':['2019-01-01', '2019-01-02', '2020-01-01', '2020-02-02'],
        'tweets':["aaa", "bbb", "ccc", "ddd"]}

df = pandas.DataFrame(data)

df['daate'] = pandas.to_datetime(df['date'], infer_datetime_format=True)

所以我有一个object 类型的日期和一个datetime64[ns] 类型的日期。我想知道每年每个月的行数,比如 2019-01 的两行,2020-01 和 2020-02 的一行。我还想根据日期对数据进行排序,从最旧到最新。谢谢各位!

【问题讨论】:

    标签: python pandas dataframe time-series


    【解决方案1】:

    您可以使用 groupby 来计算行数

    df['year-month'] = df['daate'].dt.strftime('%Y-%m')
    df.groupby('year-month').count()
    
                date    tweets  daate
    year-month          
    2019-01     2       2       2
    2020-01     1       1       1
    2020-02     1       1       1
    

    这是排序值的方法,ascending=True 表示从低到高,False 表示从高到低

    df.sort_values(by='daate',ascending=True)
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 2021-04-30
      • 2014-10-18
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多