【问题标题】:Expand panel data python展开面板数据 python
【发布时间】:2017-11-01 18:06:14
【问题描述】:

我正在尝试扩展以下数据。我是Stata用户,我的问题可以通过stata中的“fillin”命令解决,现在我正在尝试用python重写这个命令,但找不到任何有效的命令。

例如: ,转换这个数据框: (我的数据框比给出的例子大,这个例子只是为了说明我想要做什么)

id year X Y 1 2008 10 20 1 2010 15 25 2 2011 2 4 2 2012 3 6

到这个

id year X Y 1 2008 10 20 1 2009 . . 1 2010 15 20 1 2011 . . 1 2012 . . 2 2008 . . 2 2009 . . 2 2010 . . 2 2011 2 4 2 2012 3 6 谢谢,对不起我的英语

【问题讨论】:

    标签: python pandas stata


    【解决方案1】:

    这可以通过使用.loc[]来完成

    from itertools import product
    import pandas as pd
    
    df = pd.DataFrame([[1,2008,10,20],[1,2010,15,25],[2,2011,2,4],[2,2012,3,6]],columns=['id','year','X','Y'])
    df = df.set_index(['id','year'])
    
    # All combinations of index
    #idx = list(product(df.index.levels[0], df.index.levels[1]))
    idx = list(product(range(1,3), range(2008,2013)))
    
    df.loc[idx]
    

    【讨论】:

      【解决方案2】:

      从数据框创建一个新的多索引,然后重新索引

      years = np.tile(np.arange(df.year.min(), df.year.max()+1,1) ,2)
      ids = np.repeat(df.id.unique(), df.year.max()-df.year.min()+1)
      arrays = [ids.tolist(), years.tolist()]
      new_idx = pd.MultiIndex.from_tuples(list(zip(*arrays)), names=['id', 'year'])
      
      df = df.set_index(['id', 'year'])
      
      df.reindex(new_idx).reset_index()
      
          id  year    X       Y
      0   1   2008    10.0    20.0
      1   1   2009    NaN     NaN
      2   1   2010    15.0    25.0
      3   1   2011    NaN     NaN
      4   1   2012    NaN     NaN
      5   2   2008    NaN     NaN
      6   2   2009    NaN     NaN
      7   2   2010    NaN     NaN
      8   2   2011    2.0     4.0
      9   2   2012    3.0     6.0
      

      【讨论】:

        猜你喜欢
        • 2021-09-03
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        • 2019-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多