代码之家  ›  专栏  ›  技术社区  ›  g_p

从值列表添加或更新数据帧

  •  0
  • g_p  · 技术社区  · 6 年前

    >>> df
      name  count
    0    a      1
    1    b      2
    2    c      0
    

    我想用这个列表更新这个值

     l = ['a','b','d']
    

    所以我更新的df应该是这样的

    >>> df
      name  count
    0    a      2
    1    b      3
    2    c      0
    3    d      1
    

    我能想到的唯一方法就是使用循环。你们还有别的建议吗。 谢谢

    2 回复  |  直到 6 年前
        1
  •  3
  •   jezrael    6 年前

    Series 从列表中获取计数依据 Series.value_counts ,然后创建 df DataFrame.set_index Series.add 在一起,永远 DataFrame 使用 Series.rename_axis Series.reset_index :

    l = ['a','b','d']
    
    add = pd.Series(l).value_counts()
    print (add)
    d    1
    a    1
    b    1
    dtype: int64
    
    df1 = (df.set_index('name')['count']
             .add(add, fill_value=0)
             .astype(int)
             .rename_axis('name')
             .reset_index(name='count'))
    print (df1)
      name  count
    0    a      2
    1    b      3
    2    c      0
    3    d      1
    
        2
  •  1
  •   Erfan    6 年前

    另一种方法是将值加在彼此的顶部,然后 GroupBy.count :

    x = sorted(list(set(df['name'].tolist() + l)))
    new = pd.concat([df['name'].repeat(df['count']).to_frame()
                     , pd.DataFrame({'name':l})]).groupby('name')['name'].count()
    new = new.reindex(x, fill_value=0).reset_index(name='count')
    

    输出

    print(new)
      name  count
    0    a      2
    1    b      3
    2    c      0
    3    d      1
    
        3
  •  0
  •   Michiel.B    6 年前

    唯一的缺点是从df到dict的转换,反之亦然。

    from collections import Counter
    
    # initialize your variables
    df = pd.DataFrame({'name': ['a', 'b', 'c'],
                       'count': [1, 2, 0]})
    l = ['a', 'b', 'd']
    
    # convert to dict with name - count pairs and update with counter of l
    df_as_dict = dict(zip(df['name'].values, df['count'].values))
    df_as_dict.update(Counter(df_as_dict) + Counter(l))
    
    # create dataframe with updates values
    new_df = pd.DataFrame({'name': list(df_as_dict.keys()), 
                           'count': list(df_as_dict.values())})
    # ensure df format
    new_df = new_df.sort_values('name').reset_index(drop=True)
    
    new_df
    

    输出

       count name
    0      2    a
    1      3    b
    2      0    c
    3      1    d