简体   繁体   中英

Create new column based on other columns values with conditions

I have a dataframe like the picture below:

在此处输入图像描述

I want to create a new column as "positive_review_contents" which contains the value from the column "review_contents" and the value is corresponding with column "individual_rate" where it is equal and higher than 4.

For the new column "positive_review_contents", some corresponding rows, where the "individual_rate" is below 4, will be Null so I could assign that Null value to "No Positive"

Please help to advise me. Thank you so much!

Can you try this and let me know if it works fine?

df["positive_review_contents"] = df["individual_rate"].apply(lambda x: (review_contents+individual_rate) if x >= 4 else 'No Positive Review')

You can do it with pandas.DataFrame.apply :

def get_prc(x):
    individual_rate = x["individual_rate"]
    if individual_rate >= 4:
        return x["review_contents"] + " " + str(individual_rate)
    return "Not positive"
 
df["positive_review_contents"] = df[["individual_rate", "review_contents"]].apply(get_prc, axis = 1)

The code above applies the function get_prc row-wise.

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