python - 逐行检查并生成带有数字的文本
问题描述
我有一个这样的数据框
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,然后选择相应的主题并在文本中计数。
想要的输出:
它类似于下面的问题,但我无法获得计数,因为我们有额外的额外列并且还需要获得不同的计数要求。
解决方案
考虑一下我写的“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')
让我知道这是否有帮助:)
推荐阅读
- angular - 如何为 Angular 5 中的 api 失败编写单元测试用例?
- google-bigquery - Bigquery:按月分组时间戳
- python - 如何删除引用到对象的所有嵌套对象?
- java - docx4j:使用 Java 读取 docx 文件的两个书签之间的数据
- java - android更新后Gradle同步错误(compileSdkVersion未指定)
- x86 - x86 程序集中的 ds:0x402000 和 DWORD PTR ds:0x402000 有什么区别?
- android - AAssetManager 无法从共享库访问原始资源
- xpath - 使用 com.jcabi.jcabi-xml 时,“前缀必须解析为命名空间:p”
- opencv - How to make image source change after handle without display another one on canvas output (OpenCV.js)
- python - 无论我放什么图像,我的 CNN 模型都只预测第一类