代码之家  ›  专栏  ›  技术社区  ›  Ahmad.Masood

pandas:使用loc获取固定行数

  •  -1
  • Ahmad.Masood  · 技术社区  · 6 年前

    假设我们有以下数据帧。

    tempDataframe = 
    
    Col1 Col2
    1   2
    1   4
    2   5
    

    运行以下代码后,我希望得到以下结果:

    tempDataframe = tempDataframe.set_index('Col1')
    tempDataframe.loc[[1,2]]
    
    Col1 Col2
    1    2
    1    4
    2    5
    2    0
    

    对于每个索引,至少应该有 结果。对于小于两个值的条目,应返回一个带有零的额外条目。

    2 回复  |  直到 6 年前
        1
  •  1
  •   BENY    6 年前

    在您的情况下,您需要使用 cumcount

    df['New']=df.groupby(level=0).cumcount()
    df.set_index('New',append=True,inplace=True)
    df.unstack(fill_value=0).stack().groupby(level=0).head(2)
    Out[436]: 
              Col2
    Col1 New      
    1    0       2
         1       4
    2    0       5
         1       0
    
        2
  •  0
  •   Martien Lubberink    6 年前

    看起来你想用这个 reindex 带填充值。