python - Python 3.X Pandas 中的简单 IF 语句不起作用
问题描述
这应该是一个简单的 IF 语句,它根据条件进行更新,但它不起作用。
这是我的代码
df["Category"].fillna("999", inplace = True)
for index, row in df.iterrows():
if (str(row['Category']).strip()=="11"):
print(str(row['Category']).strip())
df["Category_Description"] = "Agriculture, Forestry, Fishing and Hunting"
elif (str(row['Category']).strip()=="21"):
df["Category_Description"] = "Mining, Quarrying, and Oil and Gas Extraction"
打印声明
print(str(row['Category']).strip())
工作正常,但 Category_Description 列的更新不起作用。
输入数据有以下代码
Category Count of Records
48 17845
42 2024
99 1582
23 1058
54 1032
56 990
32 916
33 874
44 695
11 630
53 421
81 395
31 353
49 336
21 171
45 171
52 116
71 108
61 77
51 64
62 54
72 51
92 36
55 35
22 14
更新导致
Agriculture, Forestry, Fishing and Hunting 41183
这是 repl.it 上的数据集和代码的一个小样本 https://repl.it/@RamprasadRengan/SimpleIF#main.py 当我用这些数据运行上面的代码时,我仍然看到同样的问题。
我在这里想念什么?
解决方案
您正在执行行操作,但在“IF”语句中应用了数据框更改。这会将值应用于所有记录。
尝试一下:
def get_category_for_record(rec):
if (str(row['Category']).strip()=="11"):
return "Agriculture, Forestry, Fishing and Hunting"
elif (str(row['Category']).strip()=="21"):
return "Mining, Quarrying, and Oil and Gas Extraction"
df["category"] = df.apply(get_category_for_record, axis = 1)
推荐阅读
- vba - 从 VBA 运行多个 Matlab 脚本
- java - 访问 SQL IDENTITY 值会阻止 Spring @Sql 测试在不同的数据库上运行
- f# - 如何使用 F# 在 akka.net 中创建子演员?
- list - 查找列表中出现次数的函数
- docker - 我可以在容器初始化时创建解析器类吗?
- c - 为什么在这里使用 strdup()?
- ios - “捆绑
操作尝试在具有 CurrentValueSubject 绑定的 TextField 上每帧更新多次 - python-3.x - 使用 gitpython 推送到 GitLab 后如何获取信息
- c - 是否可以在内核模块的根路径中创建目录?
- xcode - 导航栏被隐藏但不允许在 SwiftUI 中单击标题按钮