社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Acccumulation  »  全部回复
回复总数  3
5 年前
回复了 Acccumulation 创建的主题 » Python和Pandas:构造lambda参数

首先是一个样式注释:您应该使用更多的回车符,并且您的变量名相当长(包括名称中的“score”和“value”有点多余)。我相信以下功能仍然有效,不需要侧滚:

df['composition_comment'] = df['composition_score'].apply(
    lambda element: comp_comment_a if element <= (comp_score * 1) 
        else element >= (comp_score *.90))

至于发生了什么,上面的代码告诉Python您想要 comp_comment_a 如果 element 小于或等于 comp_score * 1 ,否则您需要 element >= (comp_score *.90) 和 元素>=(综合得分*.90) 是一个布尔值。我不完全清楚你的预期结果是什么,但根据我对你想要什么的猜测,你应该有 and 而不是 else .您的代码可以变得更干净,例如:

import pandas as pd

df = pd.read_csv('stack.csv')
comp_score = 40  #calculated by another process

comp_comments = ["Good work.", "Satisfactory work.", "Improvement needed.", 
    "Unsatisfactory work."]

def score_to_comment(score):
    if score > comp_score:
        #it's not clear what you want to do in this case
        #but this follows your original code
        return None
    if score >= comp_score * .9:
        return comp_comments[0]
    if score >= comp_score * .8:
       return comp_comments[1]
    if score >= comp_score * .7:
       return comp_comments[2]
    return comp_comments[3]

df['composition_comment'] = df['composition_score'].apply(score_to_comment)

df.to_csv('stack.csv', index=False)
4 年前
回复了 Acccumulation 创建的主题 » 除了使用Python的集合之外,还使用If-Else语句

首先 input 将用户输入作为字符串。所以即使他们进入 1 ,这与你的套装不匹配,因为你的套装是 int ,他们的输入是 一串 '1' ,而不是整数 1. .而且,不需要使用一套。A. range 对象更容易生成,因为它包含多个数字,所以变量名应该是复数。你的缩进也不正确。我不明白这是怎么回事 f 在输入函数中,如果需要多行字符串,则需要三个引号。此外,如果你的字符串中有回车符 \n 在字符串中有两个换行符;我不确定这是不是有意的。这样做的一个方法是:

fortune_nums = [str(num) for num in range(1,10)]
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
if user_num in fortune_nums:
    print(user_num)
else:
    print('Error')

如果你想变得更时尚,你可以保持 fortune_nums 作为int,然后尝试将输入转换为int,捕捉无效的文字错误:

fortune_nums = range(1,10)
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
try:
    if(int(user_num) in fortune_nums):
        print(user_num)
except ValueError:
    print("That's not a valid integer!")

代码的第二行创建了一个范围对象,然后用于循环的其余部分,代码不会修改该范围对象。即使你改变了步长,也不会只改变范围的下一个元素,而是会改变整个范围对象(也就是说,将步长改为2会使 每一个 元素在范围内(比上一个元素多2个)。如果你真的想,你可以创建一个命名对象,并在for循环中修改它,但这将是一件相当麻烦的事情。

您还可以使用另一个与主循环不同的索引。例如:

actual_index = 1
for for_loop_index in range(1,100):
   if condition1:
        actual_index = actual_index + 1
   if condition2:
        actual_index = actual_index + 2
   if actual_index > 99:
        break

这基本上是一个while循环,除非对迭代次数有严格限制,这在某些用例中可能很有用。