【问题标题】:Count rows with 2 different Date-time columns in python在python中计算具有2个不同日期时间列的行
【发布时间】:2021-03-31 06:16:36
【问题描述】:

我有一个包含 2 个日期列的数据框:

 ---------------------------- 
| date_created |  date_ended |
|--------------| ----------- |
|20/12/01      | 20/11/01    |
|20/12/01      | 20/12/02    |
|20/12/02      | 20/12/02    |
|20/12/02      | 20/12/03    |
|20/12/02      | 20/12/03    |
|20/12/03      | 20/12/03    |
|20/12/03      | 20/12/04    |
 ----------------------------

当两列值(日期)相同时,我需要计算两列中的行数,即我需要的输出:

 ------------------------------------------
| date_index   |created_count| ended_count |
|--------------| ----------- | ----------- |
|20/11/01      |      0      |      1      |
|20/12/01      |      2      |      0      |
|20/12/02      |      3      |      2      |
|20/12/03      |      2      |      3      |
|20/12/04      |      0      |      1      |
 ------------------------------------------

我一直在逐列计算各个列,然后匹配相同的日期索引。有什么干净的方法可以实现这一目标吗?如果有人可以提供帮助。

【问题讨论】:

    标签: python pandas dataframe datetime python-datetime


    【解决方案1】:

    DataFrame.applyvalue_counts 一起使用,将不匹配的NaN 替换为0 并最后转换为整数:

    df = df.apply(pd.value_counts).fillna(0).astype(int)
    print (df)
             date_created  date_ended
    20/11/01             0           1
    20/12/01             2           0
    20/12/02             3           2
    20/12/03             2           3
    20/12/04             0           1
    

    如果想要过滤列进行处理:

    cols = ['date_created','date_ended']
    df = df[cols].apply(pd.value_counts).fillna(0).astype(int)
    print (df)
    
              date_created  date_ended
    20/11/01             0           1
    20/12/01             2           0
    20/12/02             3           2
    20/12/03             2           3
    20/12/04             0           1
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      res = pd.concat((df['date_created'].value_counts(),
                       df['date_ended'].value_counts()),
                        axis=1, sort=True).fillna(0).astype(int)
      print(res)
      

      输出

                date_created  date_ended
      20/11/01             0           1
      20/12/01             2           0
      20/12/02             3           2
      20/12/03             2           3
      20/12/04             0           1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-03
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多