简体   繁体   中英

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

how do i edit the following script to save the outputs as new variables in the original dataframe?

AKA: instead of the print function, have the output be saved as a new variable for each if elif statement?

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

ie, : new_model_core_incentives or used_model_core_incentives as a new variable in the dataframe and new_word and old_word as a new variable in the dataframe?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM