python - 根据 Pandas DataFrame 中其他列的条件创建新列
问题描述
我有这个数据框:
+------+--------------+------------+
| ID | Education | Score |
+------+--------------+------------+
| 1 | High School | 7.884 |
| 2 | Bachelors | 6.952 |
| 3 | High School | 8.185 |
| 4 | High School | 6.556 |
| 5 | Bachelors | 6.347 |
| 6 | Master | 6.794 |
+------+--------------+------------+
我想创建一个对分数列进行分类的新列。我想将其标记为:“坏”、“好”、“非常好”。
这可能看起来像这样:
+------+--------------+------------+------------+
| ID | Education | Score | Labels |
+------+--------------+------------+------------+
| 1 | High School | 7.884 | Good |
| 2 | Bachelors | 6.952 | Bad |
| 3 | High School | 8.185 | Very good |
| 4 | High School | 6.556 | Bad |
| 5 | Bachelors | 6.347 | Bad |
| 6 | Master | 6.794 | Bad |
+------+--------------+------------+------------+
我怎样才能做到这一点?
提前致谢
解决方案
import pandas as pd
# initialize list of lists
data = [[1,'High School',7.884], [2,'Bachelors',6.952], [3,'High School',8.185], [4,'High School',6.556],[5,'Bachelors',6.347],[6,'Master',6.794]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'Education', 'Score'])
df['Labels'] = ['Bad' if x<7.000 else 'Good' if 7.000<=x<8.000 else 'Very Good' for x in df['Score']]
df
ID Education Score Labels
0 1 High School 7.884 Good
1 2 Bachelors 6.952 Bad
2 3 High School 8.185 Very Good
3 4 High School 6.556 Bad
4 5 Bachelors 6.347 Bad
5 6 Master 6.794 Bad
推荐阅读
- json - 使用 Django / Python 为 Typeahead / Bloodhound 提供远程 JSON 数据
- python - “DBSCAN”对象没有使用 GridSearchCV 和管道的属性“预测”
- git - 合并后重写分支上的历史记录
- ruby - 来自 ruby 服务器的 fork 进程
- flutter - 插件 `XXXXX` 使用了已弃用的 Android 嵌入版本
- next.js - 如何为下一个js图像添加边框半径?
- javascript - 如果我单击反应 js 中的关闭按钮,如何更改状态
- xamarin - 如何在 Xamarin 中获取绑定之外的数据
- java - 无法从 Spring Boot 应用程序和 SQL Developer 访问 Docker 上的 DB2 数据库
- php - 如果在 laravel 自定义验证中包含多个值,则不会验证输入数组