首页 > 解决方案 > 逐行检查并生成带有数字的文本

问题描述

我有一个这样的数据框

import pandas as pd

raw_data = {'ID': [101,101,102,101,102],
            'Loc':['IN','IN','NY','IN','NY'],
            'Sub1':['A','B','C','D','E'],
            'Sub2':['F','G','H','I','J'],
            'Sub3':['K','L','M','N','O'],
        'S_score1': [1, 0, 0, 6,0], 
        'S_score2': [0, 1, 0, 6,0], 
        'S_score3': [0, 1, 0, 6,0], 
        }

df2 = pd.DataFrame(raw_data, columns = ['ID','Loc','Sub1','Sub2','Sub3','S_score1', 'S_score2', 'S_score3'])

有数据集:

有

我想检查分数列并检查分数是否大于 1,然后选择相应的主题并在文本中计数。

想要的输出:

想要的输出

它类似于下面的问题,但我无法获得计数,因为我们有额外的额外列并且还需要获得不同的计数要求。

逐行值检查并生成文本

标签: pythonpython-3.xpandas

解决方案


考虑一下我写的“df”意味着你写的“df2”。

df['AuxIndex'] = [i for i in range(len(df))]


def ScoreText(index):

    Sub1 = df['Sub1'][index]
    Sub2 = df['Sub2'][index]
    Sub3 = df['Sub3'][index]

    Score1 = df['S_score1'][index]
    Score2 = df['S_score2'][index]
    Score3 = df['S_score3'][index]

    if(Score1 + Score2 + Score3 == 0):

        return 'You have not scored'

    else:

        scoreText = 'You have scored on '+ '{x}{y}{z}'.format(x = ' {}({})'.format(Sub1,Score1) if Score1 > 0 else '',
                                                              y = ' {}({})'.format(Sub2,Score2) if Score2 > 0 else '',
                                                              z = ' {}({})'.format(Sub3,Score3) if Score3 > 0 else '' )

    return scoreText



df['S_Text'] = df['AuxIndex'].map(lambda i: ScoreText(i))

df.drop(columns = 'AuxIndex')

在此处输入图像描述

让我知道这是否有帮助:)


推荐阅读