【问题标题】:mix the information of all columns in a single column将所有列的信息混合在一个列中
【发布时间】:2021-04-28 09:13:34
【问题描述】:

我有一个这样的数据集:

df = pd.DataFrame({'ID':["a"," b", "c","d", "e"],
               'P1': [10, 28, 34, 56, 78],
              'P2':[ 90, 54, 54, 32, 16],
              'P3':[14, 15, 24, 90,34]})

其中包含每个问题的学生成绩。我需要创建一个名为“Notes”的新列 其中包含一列中所有问题的成绩。 输出必须如下所示:

【问题讨论】:

    标签: python pandas jupyter-notebook


    【解决方案1】:

    请在使用 iloc 访问器隔离所需列之后尝试 to_dict。

    df['notes']=df.iloc[:,1:].to_dict('records')
    

    如果您需要包含总计,我们可以使用列过滤器,分配总计和注释如下;

    df=df.assign(Total=df.filter(regex='^P', axis=1).sum(1),notes=df.filter(regex='^P', axis=1).to_dict('records'))
    

    如果字典括号是一个问题。你可以把它们去掉

    df.notes.astype(str).str.strip('{}')
    

    【讨论】:

    • 以防万一有人无法通过.iloc[:,1:]df.filter(like='P').to_dict('records')访问特定列
    • 感谢@Pygirl 的建议。 ws 在添加的过程中。我更喜欢以 P ^P 开头的正则表达式
    • @ansev 我们不应该仅仅为了用; 替换: 而提供过于复杂的解决方案。我提倡可读的代码。如果有方法,我不需要重新发明轮子
    • @ansev,什么会阻止他访问df.notes.astype(str).str.strip('{}')?还是用更短更易读的代码来回答问题?
    【解决方案2】:

    用途:

    #Calculate Total
    df['Total'] = df.filter(regex='P').sum(axis=1)
    #Create Notes
    df['Notes'] = df.filter(regex='P').astype(str)\
        .apply(lambda row: ','.join(row.index + ';' + row), axis=1)
    print(df)
    
    
       ID  P1  P2  P3  Total              Notes
    0   a  10  90  14    114  P1;10,P2;90,P3;14
    1   b  28  54  15     97  P1;28,P2;54,P3;15
    2   c  34  54  24    112  P1;34,P2;54,P3;24
    3   d  56  32  90    178  P1;56,P2;32,P3;90
    4   e  78  16  34    128  P1;78,P2;16,P3;34
    

    【讨论】:

      【解决方案3】:

      尝试使用lambdamap

      p_val = df.filter(like='P')
      
      comb = lambda x: [f"{key}:{val}" for key,val in zip(p_val.columns, x)] 
      df['Notes'] = pd.Series(list(map(comb,p_val.values.tolist()))).str.join(',')
      

      df:

          ID  P1  P2  P3  Notes
      0   a   10  90  14  P1:10,P2:90,P3:14
      1   b   28  54  15  P1:28,P2:54,P3:15
      2   c   34  54  24  P1:34,P2:54,P3:24
      3   d   56  32  90  P1:56,P2:32,P3:90
      4   e   78  16  34  P1:78,P2:16,P3:34
      

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 1970-01-01
        • 2020-07-11
        • 1970-01-01
        • 2017-06-20
        • 2022-07-27
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        相关资源
        最近更新 更多