python - 如何将if elif语句的输出保存到python数据框中的新变量?
问题描述
如何编辑以下脚本以将输出保存为原始数据框中的新变量?
AKA:是否将输出保存为每个 if elif 语句的新变量,而不是 print 函数?
import re
df = pd.read_excel('edmundstest.xlsx')
for Keyword, Landing_Page in zip(df["Keyword"], df["Landing_Page"]):
# the url
if "/2019/" in Landing_Page:
new_model_core_incentives = Landing_Page
print(f"new_model_core_incentives {new_model_core_incentives}")
elif re.search("/(?:(?:20)|(?:19))\d{2}/", Landing_Page):
used_model_core_incentives = Landing_Page
print(f"used_model_core_incentives {used_model_core_incentives}")
# the "keywords"
if "2019" in Keyword:
new_word = Keyword
print(f"new_word {new_word}")
elif re.search("/(?:(?:20)|(?:19))\d{2}/", Keyword) is None:
old_word = Keyword
print(f"old_word {old_word}")
即:new_model_core_incentives
或used_model_core_incentives
作为数据框中的新变量new_word
和old_word
作为数据框中的新变量?
解决方案
You could use a dictionary:
dict[Keyword]=f"new_model_core_incentives {new_model_core_incentives}"
dict2[Keyword]=f"old_word {old_word}"
Something like this:
import re
df = pd.read_excel('edmundstest.xlsx')
dict, dict2 = {}, {}
for Keyword, Landing_Page in zip(df["Keyword"], df["Landing_Page"]):
# the url
if "/2019/" in Landing_Page:
new_model_core_incentives = Landing_Page
print(f"new_model_core_incentives {new_model_core_incentives}")
elif re.search("/(?:(?:20)|(?:19))\d{2}/", Landing_Page):
used_model_core_incentives = Landing_Page
dict[Keyword]=f"new_model_core_incentives {new_model_core_incentives}"
# the "keywords"
if "2019" in Keyword:
new_word = Keyword
print(f"new_word {new_word}")
elif re.search("/(?:(?:20)|(?:19))\d{2}/", Keyword) is None:
old_word = Keyword
dict2[Keyword]=f"old_word {old_word}"