【问题标题】:sum if the field name matches the dictionary values in python如果字段名称与python中的字典值匹配,则求和
【发布时间】:2019-11-20 08:58:05
【问题描述】:

我有一个这样的数据框

Id  Brand1  Brand2  Brand3   Brand4  Brand5
1    1       0       0        1        1
2    1       0       0        0        0
3    1       0       0        0        0
4    1       1       0        1        0

而且我还有一本每个品牌的分类字典。

categorydict = {'General': ['Brand1', 'Brand2', 'Brand3'],
 'Fueloil': ['Brand4',  'Brand5']}

现在,我想为我的categorydict 中的每个类别在我的表中添加新字段,并为每个 id 添加值的总和。

Id  Brand1  Brand2  Brand3   Brand4  Brand5  General  FuelOil
1    1       0       0        1        1       1        2
2    1       0       0        0        0       1        0
3    1       0       0        0        0       1        0
4    1       1       0        1        0       2        1

我找不到我应该使用的方法,希望能得到任何帮助

【问题讨论】:

    标签: python python-3.x pandas dataframe dictionary


    【解决方案1】:

    按字典循环并通过sum填充的键创建新列:

    for k, v in categorydict.items():
        df[k] = df.loc[:, v].sum(axis=1)
    
    print (df)
       Id  Brand1  Brand2  Brand3  Brand4  Brand5  General  Fueloil
    0   1       1       0       0       1       1        1        2
    1   2       1       0       0       0       0        1        0
    2   3       1       0       0       0       0        1        0
    3   4       1       1       0       1       0        2        1
    

    【讨论】:

      【解决方案2】:

      我更喜欢 assign 为列和值解包字典

      df = df.assign(**{k: df[v].sum(1) for k, v in categorydict.items()})
      
      Out[26]:
         Id  Brand1  Brand2  Brand3  Brand4  Brand5  General  Fueloil
      0   1       1       0       0       1       1        1        2
      1   2       1       0       0       0       0        1        0
      2   3       1       0       0       0       0        1        0
      3   4       1       1       0       1       0        2        1
      

      【讨论】:

        猜你喜欢
        • 2019-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多