[英]A simple IF statement in Python 3.X Pandas not working
這應該是一個簡單的 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”語句中應用了 dataframe 更改。 這會將值應用於所有記錄。
嘗試一下:
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)
我認為您想在 dataframe 中添加一列,將類別映射到更長的描述。 如評論中所述,分配給列會影響整個列。 但是如果使用列表,則列中的每一行都會獲得相應的值。
所以用字典來對 map 名字進行描述,建立一個列表,然后賦值。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.