簡體   English   中英

如何將if ifif語句的輸出保存到python數據幀中的新變量?

[英]how to save output of if elif statement to new variable in python dataframe?

如何編輯以下腳本以將輸出保存為原始數據框中的新變量?

AKA:將輸出保存為每個if ifif語句的新變量,而不是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_incentivesused_model_core_incentives作為數據幀中的新變量, new_wordold_word作為數據幀中的新變量?

你可以使用字典:

dict[Keyword]=f"new_model_core_incentives {new_model_core_incentives}"
dict2[Keyword]=f"old_word {old_word}"

像這樣的東西:

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}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM