【问题标题】:How to match column names with dictionary keys and add value to counter如何将列名与字典键匹配并向计数器添加值
【发布时间】:2020-09-25 04:38:05
【问题描述】:

我为每个单元格创建了一个具有二进制值的数据框,其中每一行是用户,每一列是用户可以选择(或不选择)的公司,如下所示:

company1 company2 company3
1        0        0
0        0        1
0        1        1

我创建了一个字典,将每家公司分为高、中、低价值公司:

{'company1': 'high',
'company2': 'low',
'company3': 'low'}

目前有些公司在数据框中但不在字典中,但这应该会很快得到解决。我想为每个用户选择高、中或低价值公司的次数创建变量。最终应该是这样的:

company1 company2 company3 total_low total_mid total_high
1        0        0         0         0         1
0        0        1         1         0         0
0        1        1         2         0         0

我开始创建一个循环来完成此操作,但我不确定如何将列名与字典键/值匹配,或者这是否是最有效的方法(有 ~18,000 行/用户和 ~共 100 列/公司):

total_high = []
total_mid = []
total_low = []
for row in range(df.shape[0]):
    for col in range(df.shape[1]):
        if df.iloc[row,col] == 1:
            # match column name with dict key and add value to 
            # counter

【问题讨论】:

    标签: python pandas loops dataframe dictionary


    【解决方案1】:

    一种可能的方法:

    d = {'company1': 'high',
         'company2': 'low',
         'company3': 'low'}
    
    df.join(df.rename(columns=d)
             .groupby(level=0, axis=1).sum()
             .reindex(['low','mid','high'], axis=1, fill_value=0)
             .add_prefix('total_')
           )
    

    输出:

       company1  company2  company3  total_low  total_mid  total_high
    0         1         0         0          0          0           1
    1         0         0         1          1          0           0
    2         0         1         1          2          0           0
    

    【讨论】:

    • 'columns=d' 中的 d 应该是什么?我收到一条错误消息,提示“未定义名称 'd'”
    【解决方案2】:

    不像@Quang Hoang 那样短,而是另一种方式;

    融化数据框

    df2=pd.melt(df,  value_vars=['company1', 'company2', 'company3'])
    

    映射字典创建另一列total

    df2['total']=df2.variable.map(d)
    

    旋转highlow 并添加中间并加入df

    compa=['low','medium','high']
    df.join(df2.groupby(['variable','total'])['value'].sum().unstack('total', fill_value=0).reindex(compa,axis=1, fill_value=0).add_prefix('total_').reset_index().drop(columns=['variable']))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2021-12-16
      • 2022-12-08
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多