社区所有版块导航
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学习  »  Python

Python和Pandas:构造lambda参数

Daniel Hutchinson • 3 年前 • 1567 次点击  

我正在用Python和Pandas编写一个脚本,它使用lambda语句根据分配给每行的数字等级在csv列中编写预格式化的注释。虽然我能在很多系列中做到这一点,但我在一个案例中遇到了困难。

以下是csv的结构:

enter image description here

下面是编写新专栏的工作代码 composition_comment (我相信有一种方法可以更简洁地表达这一点,但我仍在学习Python和Pandas。)

import pandas as pd

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

composition_comment_a_level = "Good work." # For scores falling between 100 and 90 percent of composition_score_value.
composition_comment_b_level = "Satisfactory work." # For scores between 89 and 80.
composition_comment_c_level = "Improvement needed." # For scores between 79 and 70.
composition_comment_d_level = "Unsatisfactory work." # For scores below 69.

df['composition_comment'] = df['composition_score'].apply(lambda element: composition_comment_a_level if element <= (composition_score_value * 1) else element >= (composition_score_value *.90))
df['composition_comment'] = df['composition_score'].apply(lambda element: composition_comment_b_level if element <= (composition_score_value *.899) else element >= (composition_score_value *.80))
df['composition_comment'] = df['composition_score'].apply(lambda element: composition_comment_c_level if element <= (composition_score_value *.799) else element >= (composition_score_value *.70))
df['composition_comment'] = df['composition_score'].apply(lambda element: composition_comment_d_level if element <= (composition_score_value *.699) else element >= (composition_score_value *.001))

df 

df.to_csv('stack.csv', index=False)

预期产出为:

enter image description here

但实际产出是:

enter image description here

你知道为什么会这样吗 True 正在写入的值,以及为什么最后一行处理正确?感谢您的帮助。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133719
文章 [ 6 ]  |  最新文章 3 年前