【问题标题】:Map values of multiple dataframes and fill columns映射多个数据框的值并填充列
【发布时间】:2018-01-17 09:44:21
【问题描述】:

假设我有以下三个数据框:

数据框 1:

df1 = {'year': ['2010','2012','2014','2015'], 'count': [1,1,1,1]}
df1 = pd.DataFrame(data=df1)
df1 = df1.set_index('year')
df1

year    count
2010    1
2012    1
2014    1
2015    1

数据框 2:

df2 = {'year': ['2010','2011','2016','2017'], 'count': [2,1,3,1]}
df2 = pd.DataFrame(data=df2)
df2 = df2.set_index('year')
df2

year    count
2010    2
2011    1
2016    3
2017    1

数据框 3:

df3 = {'year': ['2010','2011','2012','2013','2014','2015','2017'], 'count': [4,2,5,4,4,1,1]}
df3 = pd.DataFrame(data=df3)
df3 = df3.set_index('year')
df3

year    count
2010    4
2011    2
2012    5
2013    4
2014    4
2015    1
2017    1

现在我想要三个包含所有年份和计数的数据框。例如,如果 df1 缺少年份 2011、2013、2016、2017,则这些年份将添加到 df1 的索引中,每个新添加的索引的计数为 0。

所以对于 df1,我的输出将是这样的:

year    count
2010    1
2012    1
2014    1
2015    1
2011    0
2013    0
2016    0
2017    0

对于 df2 和 df3 也是如此。谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以将unionreindex 一起使用:

    idx = df1.index.union(df2.index).union(df3.index)
    print (idx)
    Index(['2010', '2011', '2012', '2013', 
           '2014', '2015', '2016', '2017'], dtype='object', name='year')
    

    另一种解决方案:

    from functools import reduce
    idx = reduce(np.union1d,[df1.index, df2.index, df3.index])
    print (idx)
    
    ['2010' '2011' '2012' '2013' '2014' '2015' '2016' '2017']
    

    df1 = df1.reindex(idx, fill_value=0)
    print (df1)
          count
    year       
    2010      1
    2011      0
    2012      1
    2013      0
    2014      1
    2015      1
    2016      0
    2017      0
    
    df2 = df2.reindex(idx, fill_value=0)
    print (df2)
          count
    year       
    2010      2
    2011      1
    2012      0
    2013      0
    2014      0
    2015      0
    2016      3
    2017      1
    
    df3 = df3.reindex(idx, fill_value=0)
    print (df3)
          count
    year       
    2010      4
    2011      2
    2012      5
    2013      4
    2014      4
    2015      1
    2016      0
    2017      1
    

    【讨论】:

      【解决方案2】:

      all_years 上使用reindex 喜欢

      In [257]: all_years = df1.index | df2.index | df3.index
      
      In [258]: df1.reindex(all_years, fill_value=0)
      Out[258]:
            count
      year
      2010      1
      2011      0
      2012      1
      2013      0
      2014      1
      2015      1
      2016      0
      2017      0
      
      In [259]: df2.reindex(all_years, fill_value=0)
      Out[259]:
            count
      year
      2010      2
      2011      1
      2012      0
      2013      0
      2014      0
      2015      0
      2016      3
      2017      1
      

      【讨论】:

        【解决方案3】:

        我会选择联合你也可以使用独特的,即

        idx = pd.Series(np.concatenate([df1.index,df2.index,df3.index])).unique()
        # or idx = set(np.concatenate([df1.index,df2.index,df3.index])) 
        df1.reindex(idx).fillna(0)
        
              count
        year       
        2010    1.0
        2012    1.0
        2014    1.0
        2015    1.0
        2011    0.0
        2016    0.0
        2017    0.0
        2013    0.0
        

        【讨论】:

        • plus1,但更好的是df1.reindex(idx, fill_value=0)
        • 先生,我也有同样的情况,这使得所有答案都非常相似,所以使用了fillna,我带着联合解决方案来到这里,一秒钟就失去了它,所以变得独一无二。
        【解决方案4】:

        也可以使用迭代:

        # find missing years:
        morelist = [ j            # items which satisfy following criteria
                     # list of all numbers converted to strings:
                     for j in map(lambda x: str(x), range(2010, 2018, 1))
                     if  j not in df1.index  ]      # those not in current index
        
        # create a dataframe to be added:
        df2add = pd.DataFrame(data=[0]*len(morelist),   
                              columns=['count'], 
                              index=morelist)
        
        # add new dataframe to original:
        df1 = pd.concat([df1, df2add]) 
        
        print(df1)
        

        输出:

              count
        2010      1
        2012      1
        2014      1
        2015      1
        2011      0
        2013      0
        2016      0
        2017      0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-29
          • 1970-01-01
          • 1970-01-01
          • 2021-05-14
          • 2020-04-27
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多