有没有一种方法可以将f字符串合并到pandas-loc输出中



我正在尝试设置一个脚本,该脚本将为学生报告生成注释。为了建立一个通用模板,我使用了一个分数表,里面有他们的百分比分数。我在使用f字符串插入每个学生的名字以及任何相关的代词或教学主题时遇到了问题。

目前,我写了这样一篇文章:

report = pd.DataFrame({'Preferred Name': ['Jack', 'Jenny', 'Bob'],
'Topic': ['English', 'English', 'Maths'],
'HomeworkAv': [84.6, 68, 94.1]})
name = report['Preferred Name']
topic = report['Topic']
report.loc[report['HomeworkAv'] >= 80, 'TopicSentence'] = f"{name} has consistently demonstrated an excellent understanding for {topic} throughout the entire term. "

问题是,对于f字符串中每次插入变量,它都会列出该变量中的每个值。我知道问题是什么,但我不确定如何解决。

有没有办法让我做到这一点?

您可以使用apply语句来完成它。

以下是我的操作方法:

import pandas as pd
report = pd.DataFrame({'Preferred Name': ['Jack', 'Jenny', 'Bob'],
'Topic': ['English', 'English', 'Maths'],
'HomeworkAv': [84.6, 68, 94.1]})
report['TopicSentence'] = report.apply(lambda x: f"{x['Preferred Name']} has consistently demonstrated an excellent understanding for {x['Topic']} throughout the entire term." if x['HomeworkAv'] >= 80 else None, axis=1)

print (report)

或者你也可以这样做:

notes = "{} has consistently demonstrated an excellent understanding for {} throughout the entire term."
report['TopicSentence'] = report.apply(lambda x: notes.format(x['Preferred Name'],x['Topic']) if x['HomeworkAv'] >= 80 else None, axis=1)

输出为:

Preferred Name  ...                                                                              TopicSentence
0           Jack  ...  Jack has consistently demonstrated an excellent understanding for English throughout t...
1          Jenny  ...                                                                                       None
2            Bob  ...  Bob has consistently demonstrated an excellent understanding for Maths throughout the ...

如果你想将.loc()方法与f-string一起使用来实现任务,你可以这样做:

report.['TopicSentence'] = ''     # initialize the sentence to ''
report.loc[report['HomeworkAv'] >= 80, 'TopicSentence'] = report.loc[report['HomeworkAv'] >= 80].apply(lambda x: f"{x['Preferred Name']} has consistently demonstrated an excellent understanding for {x['Topic']} throughout the entire term. ", axis=1)

print(report)
Preferred Name    Topic  HomeworkAv                                                                                           TopicSentence
0           Jack  English        84.6  Jack has consistently demonstrated an excellent understanding for English throughout the entire term. 
1          Jenny  English        68.0                                                                                                        
2            Bob    Maths        94.1     Bob has consistently demonstrated an excellent understanding for Maths throughout the entire term. 

使用numpy它是fast

import numpy as np
report['HomeworkAv'] = np.where(report['HomeworkAv'] >= 80 , report['Preferred Name'] +  'has consistently demonstrated an excellent understanding for' + report['Topic'] + 'throughout the entire term', '')

注意:如果您有多种情况,请使用np.select

最新更新