【问题标题】:Grouping of rows in a dataframe based on the date column根据日期列对数据框中的行进行分组
【发布时间】:2018-06-22 06:26:05
【问题描述】:

我正在尝试使用 groupby 根据类似的日期行和以下代码对以下数据进行分组,但它不起作用:

df = df.reset_index()       
df = df.groupby(on='date')

我无法使用正确的语法:

输入:

预期结果:

谁能给我一些建议?

【问题讨论】:

    标签: python python-3.x pandas group-by pandas-groupby


    【解决方案1】:

    您可以将groupbybfillffill 一起使用。然后删除重复项。

    要按索引分组,请使用level=0

    df = pd.DataFrame([['2017/06/22', 49.8, 281.6, np.nan],
                       ['2017/06/22', np.nan, np.nan, 36.1],
                       ['2017/06/23', 49.6, 280.2, np.nan],
                       ['2017/06/23', np.nan, np.nan, 35.9]],
                      columns=['date', 'ratio', 'local', 'usd'])
    
    df = df.set_index('date')
    g = df.groupby(level=0)
    df = g.bfill().ffill().drop_duplicates()
    
    print(df)
    
                ratio  local   usd
    date                          
    2017/06/22   49.8  281.6  36.1
    2017/06/23   49.6  280.2  35.9
    

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多