Python3.X中的一个简单IF语句不起作用
这应该是一个简单的IF语句,它根据条件进行更新,但不起作用 这是我的密码Python3.X中的一个简单IF语句不起作用,python,python-3.x,pandas,Python,Python 3.x,Pandas,这应该是一个简单的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[&quo
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 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上的代码
当我用这些数据运行上面的代码时,我仍然看到相同的问题
这里缺少什么?您正在执行一个行操作,但在“IF”语句中应用了数据帧更改。这将把这些值应用于所有记录 找个时间试试,比如:
def get_category_for_record(rec):
如果(str(行['Category']).strip()=“11”):
返回“农业、林业、渔业和狩猎”
elif(str(row['Category']).strip()=“21”):
返回“采矿、采石和油气开采”
df[“category”]=df.apply(为记录获取类别,轴=1)
我想您应该在数据框中添加一列,将类别映射到更长的描述。如注释中所述,对列的赋值会影响整个列。但如果使用列表,则列中的每一行都会获得相应的值
所以,使用字典将名称映射到描述,建立一个列表,并分配它
import pandas as pd
category_map = {
"11":"Agriculture, Forestry, Fishing and Hunting",
"21":"Mining, Quarrying, and Oil and Gas Extraction"}
df = pd.DataFrame([["48", 17845],
[" 11 ", 88888],
["12", 33333],
["21", 999]],
columns=["category", "count of records"])
# cleanup category and add description
df["category"] = df["category"].str.strip()
df["Category_Description"] = [category_map.get(cat, "")
for cat in df["category"]]
# alternately....
#df.insert(2, "Category_Description",
# [category_map.get(cat, "") for cat in df["category"]])
print(df)
“不工作”是含糊不清的,而且你有足够高的知名度,知道给一个机会的重要性。约翰道歉。也许我应该附加一个数据集的小样本。让我试着这样做。你好,Ravan,同样的问题请检查一下:我认为上面的repl编辑器正在运行main.py,而不管打开的是什么文件。你能检查一下它的行为吗。